Saeid Shoja
Saeid Shoja

Reputation: 247

How can I extract keys and values from a nested object of objects?

This is a question in my last interview and I'm trying to resolve that: in this case, I want to catch values in the nested object and log them into the console.

const obj1 = {
  foo: 1,
  bar: {
    foo1: 2,
    bar1: {
      foo2: {
        foo3: 3,
        bar2: 4
      },
      bar3: 5
    }
  }
};

// output: [1,2,3,4,5] //

actually, I mean in a professional way. not with this way:

[obj1.foo, obj1.bar.foo1, obj1.bar.bar1.foo2.foo3, obj1.bar.bar1.foo2.bar2, obj1.bar.bar1.bar3]

Upvotes: 0

Views: 2865

Answers (2)

Sujon
Sujon

Reputation: 1

You can get specific property like this:

> function nestedObject (nested) {
>     for (const key in nested) {
>       if (typeof nested[key] === 'object') {
>         for (const nesty in nested[key]) {
>            console.log(nested[key][nesty]);
>         }
>       } else {
>         console.log(nested[key]);
>       }
>     }   }
>      nestedObject(obj1);

Upvotes: 0

R4ncid
R4ncid

Reputation: 7129

You can do something like this

const obj1 = {
  foo: 1,
  bar: {
    foo1: 2,
    bar1: {
      foo2: {
        foo3: 3,
        bar2: 4
      },
      bar3: 5
    }
  }
};

const getValues = (data, values= []) => {
  if(typeof data !== 'object'){
    return [...values, data]
  }
  return Object.values(data).flatMap(v => getValues(v, values))
}

console.log(getValues(obj1))

Upvotes: 6

Related Questions