[英]How to edit object array?
I want to edit JavaScript object. 我想编辑JavaScript对象。
I have an JavaScript object like this 我有一个这样的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}
]
I want to convert this object into this 我想将此对象转换为此
data_without_id = [
0: {id: 1, name: "Kelly", age: 40}
1: {id: 2, name: "Bob", age: 33}
]
What I need to do is: 我需要做的是:
Group by id
按
id
分组
Get latest value. 获得最新价值。
I tried using Array.prototype.reduce()
, but I can't get the result I need... 我尝试使用
Array.prototype.reduce()
,但无法获得所需的结果...
Using the function reduce
would be as follow: 使用
reduce
功能将如下所示:
The function reduce
for grouping and the function Object.values
for extracting the values. 该功能
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; }
You could use .reduce
by making the accumulator an object that has keys of the id
. 您可以通过使累加器成为具有
id
键的对象来使用.reduce
。 This way you can overwrite any previously seen objects which had the same id
, and then use Object.values
to get your array of objects: 这样,您可以覆盖任何先前看到的具有相同
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);
You could just simply use a for/of
loop to create a copy of the data where the last object with a particular id will always be the object returned in the output data. 您可以简单地使用
for/of
循环创建数据的副本,其中最后一个具有特定ID的对象将始终是输出数据中返回的对象。 This avoids the "grouping" part of the code but still returns the correct data. 这样可以避免代码的“分组”部分,但仍返回正确的数据。
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.