我正在尝试使用相同的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" }]
};
我创建了一个小提琴,设法获得了期望的输出,但是我敢肯定有一种更好的方法。 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>
答案 0 :(得分:2)
您可以使用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);