我正在嘗試實作我不確定從哪里開始的操作。下面是我的初始物件:
[
{ type: "1", name: "Anthony" },
{
type: "1",
name: "Linus",
},
{
type: "2",
name: "Sebastin",
},
]
我想要實作的是在陣列中移動具有相同型別并具有鍵值、命名標題和字串型別的物件。我正在嘗試產生與此等效的輸出,但我不確定從哪里開始。任何幫助都將是有用的和感激的。提前感謝<3
[
{
title: "1",
sub_items: [
{
type: "1",
name: "Anthony",
},
{
type: "1",
name: "Linus",
},
],
},
{
type: "2",
name: "Sebastin",
},
];
uj5u.com熱心網友回復:
您可以使用Array.reduce()按型別/標題對輸入項進行分組并創建所需的輸出:
const input = [{ "type":"1", "name":"Anthony" }, { "type": "1", "name": "Linus" }, { "type":"2", "name":"Sebastin" }]
const result = Object.values(input.reduce((acc, { type, name }) => {
acc[type] = acc[type] || { title: type, sub_items: [] };
acc[type].sub_items.push({ type, name });
return acc;
}, {}));
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
uj5u.com熱心網友回復:
你可以用Array.reduce
const data = [
{ type: "1", name: "Anthony" },
{
type: "1",
name: "Linus",
},
{
type: "2",
name: "Sebastin",
},
];
const output = data.reduce((acc, curr, index, list) => {
const matchNodes = list.filter((node) => node.type === curr.type);
if (matchNodes.length > 1) {
const accNode = acc.find((item) => item.title === curr.type);
if (accNode) {
accNode.sub_items.push(curr);
} else {
acc.push({
title: curr.type,
sub_items: [curr],
});
}
} else {
acc.push(curr);
}
return acc;
}, []);
console.log(output);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/505611.html
標籤:javascript 数组 json
