2 回答
TA贡献1843条经验 获得超7个赞
您可以使用.reduce()将所有具有相同名称的对象合并到一个Map. 这可以通过保留name具有该名称的对象的键和值的映射。每当您在数组中遇到新对象时,您都可以检查它是否存在于地图中。如果是这样,您可以添加到likings存储在关联对象中的数组中。true如果当前对象为,您还可以将状态更新为true。如果映射中不存在对象的名称作为键,您可以将对象添加为值,进一步的后续迭代reduce可以合并到该值中。
请参见下面的示例:
const arr = [ { name: 'jane', age: 10, status: true, likings: [{ sports: 'football', books: 'harrypotter' }], }, { name: 'sam', age: 20, status: false, likings: [{ sports: 'basketball', books: 'book1' }], }, { name: 'jane', age: 10, status: false, likings: [{ sports: 'chess', books: 'book2' }], }, { name: 'robert', age: 40, status: false, likings: [{ sports: 'carrom', books: 'book3' }], }, { name: 'jane', age: 10, status: false, likings: [{ sports: 'gaming', books: 'book4' }], }, { name: 'sam', age: 10, status: false, likings: [{ sports: 'gaming', books: 'book5' }], }];
const merged = [...arr.reduce((m, o) => {
const curr = m.get(o.name) || {};
return m.set(o.name, {...o, status: curr.status || o.status, likings: [...(curr && curr.likings || []), ...o.likings]});
}, new Map).values()]
console.log(merged);
TA贡献1829条经验 获得超13个赞
我认为我没有完全理解您的要求,尤其是关于“相似名称”的要求。因此,我假设您要根据“名称”对记录进行分组,并且所有具有相同“名称”的记录都将具有相同的“年龄”。
下面的解决方案是使用一个对象对记录进行分组,hash并继续将它们连接likings到元素中。完成后,通过调用返回对象的所有元素,Object.values()应该保持名称出现的顺序。
这是你想要的,或者至少给你一些想法?希望能帮助到你。
function merge(records) {
const hash = {};
for (let i = 0; i < records.length; i++) {
const element = records[i];
const key = element.name; // if you want to do something for "similarity", do something here.
hash[key] = {
...element,
status: (hash[key] && hash[key].status) || element.status,
likings: element.likings.concat((hash[key] && hash[key].likings) || []),
};
}
return Object.values(hash);
}
const data = [
{
name: "jane",
age: 10,
status: true,
likings: [{ sports: "football", books: "harrypotter" }],
},
{
name: "sam",
age: 20,
status: false,
likings: [{ sports: "basketball", books: "book1" }],
},
{
name: "jane",
age: 10,
status: false,
likings: [{ sports: "chess", books: "book2" }],
},
{
name: "robert",
age: 40,
status: false,
likings: [{ sports: "carrom", books: "book3" }],
},
{
name: "jane",
age: 10,
status: false,
likings: [{ sports: "gaming", books: "book4" }],
},
];
console.log(merge(data));
添加回答
举报