我有一個按ID分組的集合。每個id都包含對象數組。我想遍歷它並創建一個目標集合,它將按照示例中所示的「Id」列進行分組。我不會使用下劃線js。我必須使用javascript reduce方法來實現這一點。Groupby不使用下劃線js
var targetCollection = [{
123456: [
{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }
],
789456: [
{ "Id": "1", "name": "xxx", "age": "22" },
{ "Id": "1", "name": "yyy", "age": "15" },
{ "Id": "5", "name": "zzz", "age": "59" }
]
}]
var targetOutput = [{
123456: {
1: [{ "Id": "1", "name": "xxx", "age": "22" }, { "Id": "1", "name": "yyy", "age": "15" }],
5: [{ "Id": "5", "name": "zzz", "age": "59" }]
},
789456: {
1: [{ "Id": "1", "name": "xxx", "age": "22" }, { "Id": "1", "name": "yyy", "age": "15" }],
5: [{ "Id": "5", "name": "zzz", "age": "59" }]
}
}]
Code Snippet I have tried which didn't work
var newArray = [];
$.each(targetCollection, function (key, value) {
var newTarget = $(this);
var targetCollectionNew = newTarget.reduce(function (result, current) {
result[current.ParentAreaID] = result[current.ParentAreaID] || [];
result[current.ParentAreaID].push(current);
return result;
}, {});
newArray.push(targetCollectionNew);
});
console.log('newArray', newArray);
我試圖與陣列減少方法,它沒有工作。請幫幫我。
的解決方案是很容易的,但你嘗試過這麼遠嗎?哪些代碼不起作用? –
如果你能讓我知道解決方案,那將是非常棒的。我已經嘗試了很多東西,現在它不會退縮到你所要求的位置。 –
發佈最新代碼不應太難。否則,你只需發佈一個問題集。 –