我有一个对象,看起来像这样
const userAnswers = {
1: {id: 3, value: "Assistant manager"},
2: {id: 1, value: "I am the primary decision maker"},
3: {
1: {id: 1, name: "Water quality management", value: "On a long list of priorities", valueId: 2},
2: {id: 2, name: "Greenhouse gas reduction", value: "On a long list of priorities", valueId: 2},
3: {id: 3, name: "Finanicial management", value: "On a long list of priorities", valueId: 2},
4: {id: 4, name: "Feed management", value: "On a long list of priorities", valueId: 2}
}
}我知道我可以使用下面的代码遍历整个对象
Object.values(answers).forEach(value => { console.log(value)} )但是如果只想循环遍历3:中的嵌套对象
编辑: my console.log

发布于 2020-01-10 03:56:56
正如我在注释中所说的,您可以通过括号表示法(object["keyName"])来访问userAnswers['3']的值
const userAnswers = {
1: {id: 3, value: "Assistant manager"},
2: {id: 1, value: "I am the primary decision maker"},
3: {
1: {id: 1, name: "Water quality management", value: "On a long list of priorities", valueId: 2},
2: {id: 2, name: "Greenhouse gas reduction", value: "On a long list of priorities", valueId: 2},
3: {id: 3, name: "Finanicial management", value: "On a long list of priorities", valueId: 2},
4: {id: 4, name: "Feed management", value: "On a long list of priorities", valueId: 2}
}
}
var objectWithKey3 = userAnswers['3']
for (var obj of Object.values(objectWithKey3)){
console.log(obj)
}
发布于 2020-01-10 03:55:23
你可以试试这个
Object.values(Object.values(object1)[2]).forEach(item => console.log(item));https://stackoverflow.com/questions/59670884
复制相似问题