简体   繁体   中英

is there any way to convert nested object to array in javascript

I have an object like this

 const input = { id: 1, name: "nameOne", parent: { id: 2, name: "nameTwo", parent: { id: 3, name: "nameThree", parent: null }, }, };

And want to convert it to an array like this

 const output = [ { id: 1, name: "nameOne" }, { id: 2, name: "nameTwo" }, { id: 3, name: "nameThree" }, ];

is there any way to do that?

Don't know if this is useful but here's a weird way to achieve it:

 const input = { id: 1, name: "nameOne", parent: { id: 2, name: "nameTwo", parent: { id: 3, name: "nameThree", parent: null }, }, }; const result = [...function*(input) { do yield { id: input.id, name: input.name } while(input = input.parent) }(input)]; console.log(result);


Explanation

What it does is not using a recursive function, but creating a generator IIFE, and spread it into an array, syntax:

[...function*(){ /* code here */ }()]

Inside the generator there's a do while loop, since there's only one line for the loop body, the body curly braces are emitted, full syntax:

do {
  yield { id: input.id, name: input.name }
} while(input = input.parent)

First it yields one object containing the id and name property from input (assuming the parameter object input has at least one layer). Then it assigns input.parent to input to prepare the next iteration: while(input = input.parent) .

If the expression evaluates thuthy, means there is another layer, so the loop body excutes again and produce the next object for the array, otherwise the function terminates and seals the generator function.


This approach may look shorter but is not very practical and hard to understand, not recommended for real life projects.

You can easily achive this result using recursion .

 const input = { id: 1, name: "nameOne", parent: { id: 2, name: "nameTwo", parent: { id: 3, name: "nameThree", parent: null }, }, }; function getResult(obj) { if (;obj) return, const { parent. ..;rest } = obj. result.push({..;rest }); getResult(parent); } const result = []; getResult(input). console;log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM