【问题标题】:How to loop over an object inside of an object如何在对象内部循环对象
【发布时间】:2022-01-12 22:18:03
【问题描述】:

服务器给出以下响应:

SomeObject:{
    Object1:{
        id: 123456789,
        name: "Foo"
    },
    Object2:{
        id: 123456789,
        name: "Bar"
    }
}

是否可以循环遍历SomeObject 并同时显示Object1/Object2idname?搜索这个主要导致使用Object.keys(SomeObject).map,但是这些用于获取Object1/Object2的字符串。

【问题讨论】:

  • 预期输出是什么?
  • 最好是每个对象的 {id} {name}
  • for (const item of SomeObject) { var id = item.id; console.log(id) };
  • 使用 Object.values(obj) 而不是 Object.keys(obj)

标签: javascript arrays typescript object


【解决方案1】:

const SomeObject = { Object1: { id: 123456789, name: "Foo" }, Object2:{ id: 123456789, name: "Bar" } };

const res = 
  Object.values(SomeObject)
  .forEach(({ id, name }) => console.log(id, name));

【讨论】:

  • 所以 Object.values 返回对象,然后你在 for each 中“提取” id 和 name?我理解正确吗?
  • 是的Object#values 将返回[ { "id": 123456789, "name": "Foo" }, { "id": 123456789, "name": "Bar" } ]。使用Array#forEach,然后我们对其进行迭代,从每个项目中解构 id 和 name 并打印它们。
  • 啊好吧,这很清楚。
  • @Sylent 要清楚,这假设您知道对象架构。如果您想要更通用的方法,可以查看我的答案。这显然比一段代码更干净,但只能应用于这个特定的用例。
  • @BenjaminJamesKippax 这确实看起来很普遍。我目前正在搞乱 react 和 mongodb,我也在考虑更改服务器的响应。
【解决方案2】:

一种方法是先使用 Object.values,然后使用 forEach。

SomeObject = {
    Object1:{
        id: 123456789,
        name: "Foo"
    },
    Object2:{
        id: 123456789,
        name: "Bar"
    }
}

Object.values(SomeObject).forEach(function (value) {
     console.log(value.id);
     //value.name
});

【讨论】:

    【解决方案3】:

    另一种利用两个forin循环的方法。

        obj = {
            SomeObject: {
                Object1: {
                    id: 123456789,
                    name: "Foo"
                },
                Object2: {
                    id: 123456789,
                    name: "Bar"
                }
            }
        }
    
        for (const key in obj) {
            if (Object.hasOwnProperty.call(obj, key)) {
                const
                    obj2 = obj[key];
                for (const key2 in obj2) {
                    if (Object.hasOwnProperty.call(obj2, key2)) {
                        inner_obj2 = obj2[key2];
                        console.log(inner_obj2.id, inner_obj2.name);
                    }
                }
            }
        }

    【讨论】:

      【解决方案4】:

      因此,如果您有一个具有未知数量属性的对象,但您知道所有这些属性都是对象,您可以这样做...

      let obj = {
          prop1: {
          id: 1,
          someProp: { subId: 's1' }
        },
        propA: {
          id: 2,
          someProp: { subId: 's2' }
        },
        prop3: {
          id: 3,
          someProp: { subId: 's3' }
        }
      }
      
      /**
      * Recursively iterate an object and its properties.
      * @param {object} theObj the object to be iterated
      */
      function iterate(theObj) {
          for (const key of Object.keys(theObj)) {
              console.log(`type of ${key} = ${typeof theObj[key]}`);
              // do something
              if (typeof theObj[key] == 'object') {
                  iterate(theObj[key]);
              }
          }
      }
      
      iterate(obj);
      
      // output
      // type of prop1 = object
      // type of id = number
      // type of someProp = object
      // type of subId = string
      // type of propA = object
      // type of id = number
      // type of someProp = object
      // type of subId = string
      // type of prop3 = object
      // type of id = number
      // type of someProp = object
      // type of subId = string
      

      它绝不是完美的,但它适用于对象和数组。 甚至用这种疯狂的方式尝试过。

      let arr = [
          0,
          'test',
          {
              id: 1,
              subarr: [
                  32,
                  45,
                  76
              ],
              subObj: {
                  key:'foo',
                  lock: 'bar'
              }
          }
      ]
      
      iterate(arr);
      
      // output
      // type of 0 = number
      // type of 1 = string
      // type of 2 = object
      // type of id = number
      // type of subarr = object
      // type of 0 = number
      // type of 1 = number
      // type of 2 = number
      // type of subObj = object
      // type of key = string
      // type of lock = string
      

      【讨论】:

        【解决方案5】:

        解决这个问题的关键是Object.values() 方法,其结果可以使用for..of.forEach() 循环进行迭代:

        const SomeObject = { Object1: { id: 123456789, name: "Foo" }, Object2:{ id: 123456789, name: "Bar" } };
        
        for( let {id,name} of Object.values( SomeObject ) ) {
            console.log( id, name );
        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-26
          • 2019-03-14
          • 1970-01-01
          • 1970-01-01
          • 2017-05-12
          相关资源
          最近更新 更多