JavaScript 去掉对象数组中key值相同的对象

题目描述

去掉对象数组中key值相同的对象

题目来源及自己的思路

相关代码

let arr = [
  {"weight":10,"id":1},
  {"weight":20,"id":2},
  {"weight":30,"id":2},
  {"weight":40,"id":4},
  {"weight":50,"id":5}
];

你期待的结果是什么?实际看到的错误信息又是什么?

let arr = [
  {"weight":10,"id":1},
  {"weight":30,"id":2},
  {"weight":40,"id":4},
  {"weight":50,"id":5}
];
阅读 7.2k
4 个回答
let obj = {}
arr = arr.reduce((item, next) => {
  obj[next.id] ? '' : obj[next.id] = true && item.push(next)
  return item
}, [])
console.log(arr)

用工具函数吧,lodash uniqBy,

const arr = [
  {"weight":10,"id":1},
  {"weight":20,"id":2},
  {"weight":30,"id":2},
  {"weight":40,"id":4},
  {"weight":50,"id":5}
]
_.uniqBy(arr, 'id')

如果按照提供的参考结果,id为“2”的数据出现了两次,取的其实是后一次的值,那么上面的答案是不对的。

let obj = {}
arr.map(item => {
  obj[item.id] = item
})
let result = Object.values(obj)

不要忘了楼主本身的数据是用数组存储的,而数组本身就是有序的,而对象key却是无序的。所以使用原生对象key去重的都不是最符合要求的答案。这里给个可能的答案

[...new Map(arr.map(({id, weight})=>([id, weight]))).entries()].map(([id, weight])=>({id, weight}))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题