gpt4 book ai didi

javascript - 将对象数组转换为嵌套数组

转载 作者:行者123 更新时间:2023-12-02 21:06:25 25 4
gpt4 key购买 nike

我有对象数组

[  
{ id: 1, parent_id: null, title: 'Title 1' },
{ id: 2, parent_id: 1, title: 'Title2' },
{ id: 3, parent_id: 2, title: 'Title 3' },
{ id: 4, parent_id: null, title: 'Title 4' }
]

我需要将此数组转换为这个

[ 
{
id: 1,
parent_id: null,
children: [
{
id: 2,
parent_id: 1,
title: 'Title2',
children: [
{ id: 3, parent_id: 2, title: "Title 3" }
]
}
]
},
{id: 4, parent_id: null, title: 'Title 4' }
]

我不知道该怎么做

最佳答案

我认为这会起作用:

const original = [  
{ id: 1, parent_id: null, title: 'Title 1' },
{ id: 2, parent_id: 1, title: 'Title2' },
{ id: 3, parent_id: 2, title: 'Title 3' },
{ id: 4, parent_id: null, title: 'Title 4' }
]


const transform = arr => {
for (let i = arr.length - 1; i >= 0; i--) {
const post = arr[i]
const parent = arr.find(p => p.id === post.parent_id)
if (parent) {
if (!parent.children) {
parent.children = []
}
parent.children.push(post)
post.duplicate = true
}
}
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i].duplicate) {
arr.splice(i, 1)
}
}
return arr
}

console.log(transform(original))

这是 fiddle :https://jsfiddle.net/7h8mj63e/

关于javascript - 将对象数组转换为嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61213774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com