gpt4 book ai didi

node.js - 在 Node js中从树数组构建平面数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:15:13 26 4
gpt4 key购买 nike

我有一个无限级别的相同数组,它不限于三个级别 - 它是 n 级别数组。

最后parent_id = null;

输入数组:

{
parent_id: {
parent_id: {
parent_id: null,
_id: 5cdfcc1fb214df2da06bd0dc,
title: 'Home & Kitchen'
},
_id: 5cdfcc45b214df2da06bd0dd,
title: 'Furniture'
},
_id: 5cdfcc74b214df2da06bd0de,
title: 'Sofas'
}

预期输出数组:

[
{
_id: 5cdfcc74b214df2da06bd0de,
title: 'Sofas'
},
{
_id: 5cdfcc45b214df2da06bd0dd,
title: 'Furniture'
},
{
_id: 5cdfcc1fb214df2da06bd0dc,
title: 'Home & Kitchen'
}
]

最佳答案

function getResult(input) {
const result = [];
let curr = input;
while(curr){
result.push({
_id: curr._id,
title: curr.title
});
curr = curr.parent_id; // if there is no parent_id inside, cycle will stop
}
return result;
}

let testInput = {
parent_id: {
parent_id: {
parent_id: null,
_id: '5cdfcc1fb214df2da06bd0dc',
title: 'Home & Kitchen'
},
_id: '5cdfcc45b214df2da06bd0dd',
title: 'Furniture'
},
_id: '5cdfcc74b214df2da06bd0de',
title: 'Sofas'
};

console.log(getResult(testInput));

关于node.js - 在 Node js中从树数组构建平面数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56324708/

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