简体   繁体   中英

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]

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

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

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