如何對這個陣列進行排序?我試圖從陣列的parentId
每個元素帶來的物件陣列中分組,總是可以有不確定數量的級別,我期望的結果是我在輸出中的結果。
輸入:
[
{
"_id": "123",
"name": "ABC",
"parentID": ""
},
{
"_id": "645",
"name": "ABC 2",
"parentID": "123"
},
{
"_id": "65",
"name": "ABC 3",
"parentID": ""
}
]
輸出:
[
{
"_id": "123",
"name": "ABC",
"parentID": "",
"children": [
{
"_id": "645",
"name": "ABC 2",
"parentID": "123"
},
]
},
{
"_id": "65",
"name": "ABC 3",
"parentID": ""
}
]
感謝幫助
uj5u.com熱心網友回復:
您可以嘗試使用這種方法reduce
和filter
const input = [{
"_id": "123",
"name": "ABC",
"parentID": ""
},
{
"_id": "645",
"name": "ABC 2",
"parentID": "123"
},
{
"_id": "65",
"name": "ABC 3",
"parentID": ""
}
]
function mapChildren(data) {
//set the output with all results having no parent ids by default
let output = data.filter(x => !x.parentId)
//add children to existing results
output = data.reduce((result, current) => {
const {
parentID
} = current
if (!parentID) {
return result
}
const existingRecord = result.find(x => x._id === parentID)
if (existingRecord) {
if(!existingRecord.children) {
existingRecord.children = []
}
existingRecord.children.push({...current})
}
return result
}, output)
return output
}
console.log(mapChildren(input))
uj5u.com熱心網友回復:
這甚至適用于嵌套的孩子:
const input = [{
"_id": "123",
"name": "ABC",
"parentID": ""
},
{
"_id": "645",
"name": "ABC 2",
"parentID": "123"
},
{
"_id": "65",
"name": "ABC 3",
"parentID": "645"
}
]
function map(data) {
const childMap = data.reduce((map, child) => {
return {
...map,
[child._id]: {
...child
}
};
}, {});
const root = [];
Object.values(childMap).forEach((child) => {
if (child.parentID) {
if (childMap[child.parentID]) {
const parent = childMap[child.parentID];
if (!parent.children) {
parent.children = [];
}
parent.children.push(child)
}
} else {
root.push(child);
}
})
return root;
}
console.log(map(input));
uj5u.com熱心網友回復:
像這樣的東西是資料庫引擎的作業。您不應該在控制器方面執行此操作。模型應該以您想要的方式向您發送資料。只需要求后端人員使用這樣發送的資料進行路由,或者只是if
在您的資料決議方法中添加一些陳述句,以根據物件是否具有 parentId 來做不同的事情。
但是如果你真的想在前端做,你可以這樣做:
const data = [
{
_id: '123',
name: 'ABC',
parentID: '',
},
{
_id: '645',
name: 'ABC 2',
parentID: '123',
},
{
_id: '65',
name: 'ABC 3',
parentID: '',
},
];
const restructureData = (data) => {
const children = data.filter((object) => object.parentID);
const parents = data.filter((object) => !object.parentID);
for (let i = 0; i < children.length; i ) {
let parentIndex = parents
.map((object) => object._id)
.indexOf(children[i].parentID);
if (!parents[parentIndex].children) {
parents[parentIndex].children = [];
}
parents[parentIndex].children.push(children[i]);
}
return parents;
};
console.log(restructureData(data));
但是,這不適用于嵌套的孩子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/508257.html
標籤:javascript 数组 目的