我有一個陣列,我在其中使用 .reduce 將陣列的所有匹配 id 分組到具有 id 的新陣列中。
問題是我的輸出看起來像這樣
[
{
CHb5591f5db2a546d3af: [ [Object], [Object] ],
CH5e86016c8b894d9d87: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
}
]
我需要有這樣的輸出
[
{id: CHb5591f5db2a546d3af, content: [ [Object], [Object] ]},
{id: CH5e86016c8b894d9d87, content: [ [Object], [Object], [Object], [Object], [Object], [Object] ]}
]
這是我對減速器功能的嘗試
result = await response.reduce(function (a, i) {
a[i.messagesId] = a[i.messagesId] || []; //it generates a new property i.messagesId with an array if it does not exist (the value of not existing properties is undefined). if exist, it assign itself
a[i.messagesId].push(i);
return a;
}, Object.create({}));
uj5u.com熱心網友回復:
如果陣列中有單個物件,那么您可以輕松實作使用 Object.entries()
出于演示目的,我將其"object"用作字串
const arr = [
{
CHb5591f5db2a546d3af: [["Object"], ["Object"]],
CH5e86016c8b894d9d87: [
["Object"],
["Object"],
["Object"],
["Object"],
["Object"],
["Object"],
],
},
];
const result = Object.entries(arr[0]).map(([id, content]) => ({ id, content }));
console.log(result);
uj5u.com熱心網友回復:
可能這就是你要找的。我們有一個Array.prototype.reduce()方法可以回傳我們想要的物件陣列。
const array = [
{
'CHb5591f5db2a546d3af':
[
{ animal: 'Cat', name: 'Tom' },
{ animal: 'Dog', name: 'Bruno' }
]
},
{
'CH5e86016c8b894d9d87':
[
{ animal: 'Alligator', name: 'Mike' }
]
},
{
'CH5e86016c8b894d9d97':
undefined
}
]
const reducer = function (acc, item) {
for (const _key in item) {
acc.push({
'id': _key,
'content': item[_key]
})
}
return acc;
}
console.log(array.reduce(reducer, []))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/355735.html
標籤:javascript 节点.js 降低
上一篇:“[keyinKeys]”有效但不能與任何其他額外的鍵一起使用?
下一篇:如何將呼叫條件更改為開關盒
