![](/img/trans.png)
[英]How to merge two almost identical arrays/objects (with underscorejs or similiar libary)?
[英]How can I merge two almost identical javascript objects into one using Lodash?
我有一個數組,其中包含許多幾乎相同的對象。 我想將這些對象合二為一,同時保留它們之間不相同的數據。
這是我的數據:
[
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 1, name: 'Cat 1'}
]
},
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 2, name: 'Cat 2'}
]
}
]
我希望最終結果是:
[
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 1, name: 'Cat 1'},
{id: 2, name: 'Cat 2'}
]
}
]
任何幫助,將不勝感激!
var a1 = [
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 1, name: 'Cat 1'}
]
},
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 2, name: 'Cat 2'}
]
}
];
var a2 = [];
_.forEach(a1, function(item){
if(a2.length === 0){
a2.push(item);
}else{
_.forIn(item, function(value, key){
if(!a2[0].hasOwnProperty(key)){
a2[0][key] = value;
}else{
if(typeof value === "object" && value.length > 0){
_.forEach(value, function(v){
console.log("Pushing Item into Categories")
a2[0][key].push(v);
})
}
}
})
}
})
console.log(a2)
這不是最優雅的解決方案,但它完成了工作,並將“a1”的任何長度數組組合成一個長度為 1 對象的數組,並在它迭代的項目中組合任何嵌套數組。
所以,它也可以在下面的數組上工作……只是為了舉例:
var a1 = [
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 1, name: 'Cat 1'}
],
franks: [
{"blaH":"blah"}
]
},
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 2, name: 'Cat 2'}
] ,
franks: [
{"blaH":"blah1"}
]
} ,
{ id: 1,
title: 'The title',
description: 'The description',
categories: [
{id: 2, name: 'Cat 2'}
] ,
franks: [
{"blaH":"blah2"},
{"blaH":"blah3"}
]
}
];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.