lets say I have a JSON/object literal like so:
假设我有一个像这样的JSON /对象文字:
var animals = {
dogs : {
breed : 'breed name'
weight : 'fat'
},
cats : {
breed : 'breed name'
weight : 'fat'
}
}
because dogs and cats are the same, is there a way to abstract that key? So for example if you were doing a loop on animals, how would you have a single loop and get to breed and weight of dogs and cats with out actually using dogs and cats? The JSON I have goes a couple levels deeper than this before this happens.
因为狗和猫是一样的,有没有办法抽象出那把钥匙?因此,例如,如果你在动物身上做一个循环,你怎么会有一个循环,并实际上使用狗和猫进行繁殖和体重的狗和猫?在发生这种情况之前,我的JSON比这更深一些。
Thanks for any help!
谢谢你的帮助!
1 个解决方案
#1
1
Yes it is possible. You can loop over the keys of the object.
对的,这是可能的。您可以遍历对象的键。
for(var animalName in animals) {
currentAnimal=animals[animalName];
console.log(animalName,currentAnimal);
}
That will loop through all your animals and print the name and the associated object.
这将循环遍历所有动物并打印名称和相关对象。
Just FYI: Your JSON is invalid, you need to add commas between the properties
仅供参考:您的JSON无效,您需要在属性之间添加逗号
#1
1
Yes it is possible. You can loop over the keys of the object.
对的,这是可能的。您可以遍历对象的键。
for(var animalName in animals) {
currentAnimal=animals[animalName];
console.log(animalName,currentAnimal);
}
That will loop through all your animals and print the name and the associated object.
这将循环遍历所有动物并打印名称和相关对象。
Just FYI: Your JSON is invalid, you need to add commas between the properties
仅供参考:您的JSON无效,您需要在属性之间添加逗号