我在javascript中有一个看起来像这样的对象:
Cards:Object
|->Pack:Object
|->Spades:Array[60]
|-> 0: Object
|-> Card_img: "www.test1.com"
Card_type:"9"
1:
|-> Card_img:"www.test2.com"
Card_type:"8"
如何遍历黑桃{0,1等}中的所有key->值属性?所以它会回复给我{card_img:www.test1.com,card_img:www.test2.com}
Object.keys(cards).forEach(function (key) {
console.log(key); //gives Card how to drill down further?
});
如果我Object.keys(cards.Packs).forEach(function (key)
我得到Object.keys called on non-object
答案 0 :(得分:-1)
您不能拥有包含重复键的object
,但您可以将每张卡存储在array
中。
// a dummy cards object
var cards = {
pack: {
spades: [
{ card_img: 'blah.png', card_type: '9' },
{ card_img: 'blah.png', card_type: '10' },
]
}
};
// array to hold the spades
var spades = [];
// loop through each of the "pack" properties
for (i in cards.pack) {
// loop through each of the cards of this suit
for (j in cards.pack[i]) {
spades.push(cards.pack[i][j]);
}
}
// print out your cards
console.log(spades);