我具有无限级别的同一数组,它不限于三个级别-它是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'
}
]
答案 0 :(得分:2)
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));