col*_*lla 2 javascript node.js
我有一个像这样的对象数组:
const arr = [
{"id" : 1, "name" : "john", "age": 12, "fruits": "banana"},
{"id" : 2, "name" : "john", "age": 12, "fruits": "apple"}
{"id" : 3, "name" : "maria", "age": 13, "fruits": "grappes"}
{"id" : 4, "name" : "maria", "age": 13, "fruits": "blackberry"}
{"id" : 5, "name" : "camille", "age": 12, "fruits": "cherry"}
]
Run Code Online (Sandbox Code Playgroud)
我想为每个人(名字)创建一个对象并添加他们的对象。
所以最终的数组将是:
const arr = [
{"id" : 1, "name" : "john", "age": 12, "fruits": ["banana", "apple"]},
{"id" : 3, "name" : "maria", "age": 13, "fruits": ["grappes", "blackberry"]}
{"id" : 5, "name" : "camille", "age": 12, "fruits": ["cherry"]}
];
Run Code Online (Sandbox Code Playgroud)
我使用的实际数组非常大,这就是为什么我正在寻找最有效的方法来做到这一点。
您可以使用Array.prototype.reduce对对象进行分组。
const arr = [
{ id: 1, name: "john", age: 12, fruits: "banana" },
{ id: 2, name: "john", age: 12, fruits: "apple" },
{ id: 3, name: "maria", age: 13, fruits: "grappes" },
{ id: 4, name: "maria", age: 13, fruits: "blackberry" },
{ id: 5, name: "camille", age: 12, fruits: "cherry" },
];
const output = Object.values(
arr.reduce((res, o) => {
if (!res[o.name]) {
res[o.name] = { ...o, fruits: [] };
}
res[o.name].fruits.push(o.fruits);
return res;
}, {})
);
console.log(output);Run Code Online (Sandbox Code Playgroud)
您还可以将上面的解决方案写得更简洁:
const arr = [
{ id: 1, name: "john", age: 12, fruits: "banana" },
{ id: 2, name: "john", age: 12, fruits: "apple" },
{ id: 3, name: "maria", age: 13, fruits: "grappes" },
{ id: 4, name: "maria", age: 13, fruits: "blackberry" },
{ id: 5, name: "camille", age: 12, fruits: "cherry" },
];
const output = Object.values(
arr.reduce(
(res, o) => ((res[o.name] ||= { ...o, fruits: [] }).fruits.push(o.fruits), res),
{}
)
);
console.log(output);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
998 次 |
| 最近记录: |