简体   繁体   English

如何从嵌套的 object 个对象中提取键和值?

[英]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.这是我上次采访中的一个问题,我正试图解决这个问题:在这种情况下,我想捕获嵌套的 object 中的值并将它们记录到控制台中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从数组中的多个对象中准确提取 2 个键和值 - How can I extract exactly 2 keys and values from several objects in an array 如何使用不同的键从对象中提取2个值 - How to extract 2 values from an object with different keys 如何通过从单独的数组中匹配的字符串对象值从 3 个嵌套的 json 数组中提取对象值,然后在 html/javascript 中显示它 - How can I extract object values from 3 nested json arrays by matched string object values from a separate array and then display it in html/javascript 如何从嵌套的 object 中获取密钥? - How can I get keys from nested object? 如何从键列表和值创建嵌套对象? - How can I create a nested object from a list of keys and a value? 如何从对象数组中提取值 - How can I extract values from an array of objects 如何从数组中的对象的某些键中提取值 - How to extract values from certain keys from objects that are in an array 如何从javascript中的数组值创建对象键? - How can i create an object keys from array values in javascript? 如何使用它们的键从嵌套的 JSON 数据数组中提取最内层的值? - How can I extract innermost value from an array of nested JSON data using their keys? 如何从嵌套对象中获取所有具有值的键 - How to get all keys with values from nested objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM