Reputation: 55
I need a function that would make an array like this from an object:
let obj = {
name: 'john',
age: 25,
some: {
a: 5.5,
b: 5,
c: 'pls'
}
}
objectToArray(obj);
// Outputs: [['name', 'john'], ['age', 25], ['some', [['a',5.5], ['b', 5], ['c','pls']]]]
How exactly should I check if there is a nested object? Is the Object.entries () method a good fit?
I think we need a function that will check whether the object is passed or not, if so, it will open it and make an array of it [key, property] using the Object.entries () method, if there is also an object, then it will call itself again and for it ... Ps: i need to use only native javascript with recursion
Upvotes: 1
Views: 101
Reputation: 4419
We can recurse like this:
Check if the object passed in is an object using instanceof
.
return
whatever the value is.Convert the object to it's entries using Object.entries
.
Iterate over each [key, value]
pair using Array#map
.
objectToArray
on the value. (Jump to 1.
)This is what that looks like:
const obj = { name: 'john', age: 25, some: { a: 5.5, b: 5, c: 'pls', }, };
function objectToArray(obj) {
if (!(obj instanceof Object)) return obj;
return Object.entries(obj).map(([key, value]) => [key, objectToArray(value)]);
}
console.log(objectToArray(obj))
Upvotes: 2