[英]How to edit object array?
我想编辑JavaScript对象。
我有一个这样的JavaScript对象
data_without_id = [
0: {id: 1, name: "Mary", age: null}
1: {id: 2, name: "Bob", age: 33}
2: {id: 1, name: "Kelly", age: 40}
]
我想将此对象转换为此
data_without_id = [
0: {id: 1, name: "Kelly", age: 40}
1: {id: 2, name: "Bob", age: 33}
]
我需要做的是:
按id
分组
获得最新价值。
我尝试使用Array.prototype.reduce()
,但无法获得所需的结果...
使用reduce
功能将如下所示:
该功能reduce
了分组和功能Object.values
用于提取值。
let data_without_id = [ { id: 1, name: "Mary", age: null }, { id: 2, name: "Bob", age: 33 }, { id: 1, name: "Kelly", age: 40 }], result = Object.values(data_without_id.reduce((a, {id, name, age}) => { a[id] = {id, name, age}; return a; }, Object.create(null))); console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以通过使累加器成为具有id
键的对象来使用.reduce
。 这样,您可以覆盖任何先前看到的具有相同id
对象,然后使用Object.values
获取对象数组:
const data_without_id = [{id: 1, name: "Mary", age: null}, {id: 2, name: "Bob", age: 33}, {id: 1, name: "Kelly", age: 40}], res = Object.values(data_without_id.reduce((acc, obj) => (acc[obj.id] = obj, acc) , {})); console.log(res);
您可以简单地使用for/of
循环创建数据的副本,其中最后一个具有特定ID的对象将始终是输出数据中返回的对象。 这样可以避免代码的“分组”部分,但仍返回正确的数据。
const data_without_id = [ { id: 1, name: "Mary", age: null }, { id: 2, name: "Bob", age: 33 }, { id: 1, name: "Kelly", age: 40 } ]; function lastId(arr) { const out = []; for (let obj of arr) { // If you don't create a copy of each object the returned // data will simply be contain _references_ to the original // data. Changes in the original data will be reflected // in the returned data out[obj.id - 1] = { ...obj }; } return out; } const lastIds = lastId(data_without_id); console.log(lastIds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.