Reputation: 307
I have the same array with unlimited level, it's not limited to three levels - it's n
level array.
Last parent_id = null
;
Input Array:
{
parent_id: {
parent_id: {
parent_id: null,
_id: 5cdfcc1fb214df2da06bd0dc,
title: 'Home & Kitchen'
},
_id: 5cdfcc45b214df2da06bd0dd,
title: 'Furniture'
},
_id: 5cdfcc74b214df2da06bd0de,
title: 'Sofas'
}
Expected Output Array:
[
{
_id: 5cdfcc74b214df2da06bd0de,
title: 'Sofas'
},
{
_id: 5cdfcc45b214df2da06bd0dd,
title: 'Furniture'
},
{
_id: 5cdfcc1fb214df2da06bd0dc,
title: 'Home & Kitchen'
}
]
Upvotes: 2
Views: 535
Reputation: 7455
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));
Upvotes: 2