在不对内部对象的每个键使用 Object.entries() 的情况下循环遍历对象
Looping through an object without using Object.entries() on each key of the inner object
我想知道如何在不指定键的情况下循环遍历嵌套对象。我的意思是只取对象的名称来执行循环。有什么方法可以实现吗?
您可以在底部看到我尝试过的内容。它确实有效,但我想知道是否有一种方法可以做到这一点而无需提及 keys(hero, monster)
要循环的对象:
const characterData = {
hero: {
name: "Wizard",
avatar: "images/wizard.png",
health: 60,
diceCount: 3,
currentDiceScore: []
},
monster: {
name: "Orc",
avatar: "images/orc.png",
health: 10,
diceCount: 1,
currentDiceScore: []
},
};
Object.entries(characterData.hero).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});
您可以先遍历 Object.values() which, in this case, are the nested objects hero
, monster
and so on.. using Array.prototype.forEach(), and then your code that iterates over Object.entries() again using Array.prototype.forEach()
- 但是请注意,在
callbackFn
函数中使用了 方括号 Destructuring assignment and inside the console.log()
Template literals (Template strings):
const characterData = {hero: {name: "Wizard",avatar: "images/wizard.png",health: 60,diceCount: 3,currentDiceScore: []},monster: {name: "Orc",avatar: "images/orc.png",health: 10,diceCount: 1,currentDiceScore: []},}
Object.values(characterData)
.forEach(o =>
Object.entries(o)
.forEach(([k, v]) =>
console.log(`${k}: ${v}`)))
我想知道如何在不指定键的情况下循环遍历嵌套对象。我的意思是只取对象的名称来执行循环。有什么方法可以实现吗? 您可以在底部看到我尝试过的内容。它确实有效,但我想知道是否有一种方法可以做到这一点而无需提及 keys(hero, monster)
要循环的对象:
const characterData = {
hero: {
name: "Wizard",
avatar: "images/wizard.png",
health: 60,
diceCount: 3,
currentDiceScore: []
},
monster: {
name: "Orc",
avatar: "images/orc.png",
health: 10,
diceCount: 1,
currentDiceScore: []
},
};
Object.entries(characterData.hero).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});
您可以先遍历 Object.values() which, in this case, are the nested objects hero
, monster
and so on.. using Array.prototype.forEach(), and then your code that iterates over Object.entries() again using Array.prototype.forEach()
- 但是请注意,在
callbackFn
函数中使用了 方括号 Destructuring assignment and inside theconsole.log()
Template literals (Template strings):
const characterData = {hero: {name: "Wizard",avatar: "images/wizard.png",health: 60,diceCount: 3,currentDiceScore: []},monster: {name: "Orc",avatar: "images/orc.png",health: 10,diceCount: 1,currentDiceScore: []},}
Object.values(characterData)
.forEach(o =>
Object.entries(o)
.forEach(([k, v]) =>
console.log(`${k}: ${v}`)))