Home > Back-end >  How can I extract keys and values from a nested object of objects?
How can I extract keys and values from a nested object of objects?

Time:05-03

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]

CodePudding user response:

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))

CodePudding user response:

You can get specific property like this:

console.log(Object.entries(obj1.bar.bar1.foo2)[0])

  • Related