【问题标题】:Object.entries() and Object.keys() returning keys of nested objectsObject.entries() 和 Object.keys() 返回嵌套对象的键
【发布时间】:2022-08-18 00:57:37
【问题描述】:

我想枚举对象的键和值,但是,它包含的值也是对象(或者更准确地说,对象数组)。

我面临的挑战是嵌套对象的键和值也被返回。例如:

const myObject = {
  firstKey: [
    {
      firstNestedKey: \'asd\',
      secondNestedKey: \'bsd\',
    },
    {
      firstNestedKey: \'asd\',
      secondNestedKey: \'bsd\',
    }
  ],
  secondKey: [
    {
      firstNestedKey: \'asd\',
      secondNestedKey: \'bsd\',
    },
    {
      firstNestedKey: \'asd\',
      secondNestedKey: \'bsd\',
    }
  ],
};

console.log(Object.keys(myObject));
// Returns all keys, starting with those deeply nested 
// i.e. firstNestedKey, secondNestedKey ... firstKey, secondKey

我只想枚举外部对象的属性(即我想要一个“浅”枚举)。所以在上面的例子中,我只想记录 firstKey,secondKey。

  • 这不是一个语法有效的对象,并且没有Object.keys 不会进入嵌套对象。
  • 通过将[ ] 更改为{ } 将您的示例修复为有效的JS 后,我可以告诉您it works exactly as you want it to,没有返回嵌套键。
  • @CherryDT我很抱歉,我修正了我的例子。但是,它与您提供的内容不符。我仍然面临这个挑战。

标签: javascript


【解决方案1】:

正如 CherryDT 所评论的,您的对象语法是错误的

const myObject = {
  firstKey: {
    firstNestedKey: 'asd',
    secondNestedKey: 'bsd',
  },
  secondKey: {
    firstNestedKey: 'asd',
    secondNestedKey: 'bsd',
  },
};

console.log(Object.keys(myObject)); // [ 'firstKey', 'secondKey' ]

Object.keys returns only 1 level deep keys

【讨论】:

    猜你喜欢
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多