對不起,如果json不是完美的,我試圖將它輸入到Stackoverflow窗口中......無論如何,你可以從下面看到我想把所有單獨的對象在數組中並將它們合併到具有匹配url的第一個數組中。一旦它們合併,其他所有其他需要從陣列中刪除。通過匹配相同的鍵值來合併數組中的對象
var myArray = [
{
id: '123',
url: 'http://foo.com/1.jpg',
size: 7,
qty: 1
},
{
id: '345',
url: 'http://foo.com/5.jpg',
color: 'blue',
qty: 5
},
{
id: '678',
url: 'http://foo.com/1.jpg',
size: 8,
qty: 4
}];
我需要讓這個數組變成... 下面你可以看到,現在已經匹配URL的對象已經移到第一個匹配對象的變化'的關鍵。之後他們不再分開。它們基本上都匹配在一起併合併到同一個對象中。
var myArray = [{
id: '123',
url: 'http://foo.com/1.jpg',
variations:[
{
id : '123'
size : 7,
qty: 1
},
{
id : '678'
size : 8,
qty: 4
}],
{
id: '345',
url: 'http://foo.com/5.jpg',
color: 'blue',
qty: 5
}];
到目前爲止,我有這樣的事情:但這只是工作正在進行中。遇到麻煩帶到終點線。
myArray.forEach(function(product, index){
var sizeVariations = [];
var currentSearch = product.url;
var filteredArray = processedProducts.filter(function(obj) {
return obj.primary_image === currentSearch;
});
if(filteredArray){
filteredArray.forEach(function(data, index){
sizeVariations.push({
id : data.id,
size : data.size,
quantity : data.qty
});
});
}
});
你嘗試過什麼?你有什麼需要幫助的?請參閱[*如何創建最小,完整和可驗證的示例*](http://stackoverflow.com/help/mcve)。 – RobG
我真的不會建議創建這樣一個零碎的數據結構(即一些條目與'變體'和一些沒有)。另外,你如何確定'id'是否存在於合併條目的變體之外? – Phil
基本上,如果他們有匹配的url值,那麼我需要所有的信息都在同一個對象中 – jremi