【发布时间】: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