gpt4 book ai didi

javascript - 合并数组中的对象而不覆盖不同的值属性

转载 作者:行者123 更新时间:2023-12-01 00:36:10 25 4
gpt4 key购买 nike

我正在尝试合并具有相同 id 的数组中的对象,而不覆盖不同的值属性。

var arr = [{
Messages: { count: 1 },
Account: { key: 'TEST' },
id: 179,
Contact:
{
firstName: 'The Postman',
lastName: 'Team'
},
Tags: { name: 'forums', color: '#0091EA' }
},
{
Messages: { count: 1 },
Account: { key: 'TEST' },
id: 179,
Contact:
{
firstName: 'The Postman',
lastName: 'Team'
},
Tags: { name: 'defective', color: '#0091EA' }
}];

var tags = [];
for(var i=0; i<arr.length; i++){
tags = tags.concat(arr[i].Tags);
}

var result = arr[0];
result.Tags = tags;

console.log(result);

我的目标是拥有以下对象:

var obj =
{ Messages: { count: 1 },
Account: { key: "TEST" },
id: 179,
Contact: { firstName: "The Postman", lastName: "Team" },
Tags: [{ name: "forums", color: "#0091EA" }, { name: "defective", color: "#0091EA" }]
};

我创建了一个 fiddle ,我设法获得所需的输出,但我确信有更好的方法来做到这一点。 http://jsfiddle.net/18mLhx7j/1/

更新

根据@Harun Yilmaz发布的答案,我能够使用 Lodash reduce 实现相同的结果。我只是想知道这是否是他发布的内容的有效替代方案。

var arr = [
{ Messages: { count: 1 },
Account: { key: "TEST" },
id: 179,
Contact: { firstName: "The Postman", lastName: "Team" },
Tags: { name: "forums", color: "#0091EA" } },
{ Messages: { count: 1 },
Account: { key: "TEST" },
id: 179,
Contact: { firstName: "The Postman", lastName: "Team" },
Tags: { name: "defective", color: "#0091EA" } }
];

var interactions =_.reduce(arr, function(acc, cur) {
for (let i =0; i < Object.keys(cur).length; i++) {
let key = Object.keys(cur)[i];
if (!acc[key]) {
acc[key] = cur[key];
} else if (acc[key] && !_.isArray(acc[key]) && !_.isEqual(acc[key], cur[key])) {
var obj = [];
obj.push(acc[key]);
obj.push(cur[key]);
acc[key] = obj;
} else if (acc[key] && _.isArray(acc[key])) {
acc[key].push(cur[key]);
}
}
return acc;
}, {});

console.log(interactions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

最佳答案

您可以使用Array.reduce()拥有最终目标和 spread operator如下

var arr = [
{ Messages: { count: 1 },
Account: { key: "TEST" },
id: 179,
Contact: { firstName: "The Postman", lastName: "Team" },
Tags: { name: "forums", color: "#0091EA" } },
{ Messages: { count: 1 },
Account: { key: "TEST" },
id: 179,
Contact: { firstName: "The Postman", lastName: "Team" },
Tags: { name: "defective", color: "#0091EA" } }
];

const finalArr = arr.reduce((acc, cur) => {
const {Tags,...Rest} = cur;

acc.Tags.push(Tags);

acc = {
...Rest,
Tags: acc.Tags
};


return acc;

},{Tags:[]});
// ^^ initial object

console.log(finalArr);

关于javascript - 合并数组中的对象而不覆盖不同的值属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58117147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com