Kate
Kate

Reputation: 55

how i can make an array from an object if there are nested objects

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

Answers (1)

lejlun
lejlun

Reputation: 4419

We can recurse like this:

  1. Check if the object passed in is an object using instanceof.

    • If it is continue.
    • If not return whatever the value is.
  2. Convert the object to it's entries using Object.entries.

  3. Iterate over each [key, value] pair using Array#map.

    • Recursively call 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

Related Questions