我有一个这样的对象:
var animals_data = {
category : [
{
class : "Reptiles",
animals : [
{
image1 : "some image",
image2 : "some image 2",
name : "Snake",
description : "some description"
},
{
image1 : "another image",
image2 : "another image 2",
name : "Crocodilia",
description : "another description"
},
]
},
{
class : "Mammals",
animals : [
{
image1 : "more image",
image2 : "more image 2",
name : "Cat",
description : "more description"
},
{
image1 : "image",
image2 : "image 2",
name : "Dog",
description : "long description"
}
]
},
{
class : "Birds",
animals : [
{
image1 : "bird image",
image2 : "bird image 2",
name : "American flamingo",
description : "bird description"
},
{
image1 : "another bird image",
image2 : "another bird image 2",
name : "Atlantic puffin",
description : "another bird description"
},
]
}
]};
我想获取firstIndex的值并将它们放在不同的数组中。但是,我很难做到这一点。我做的代码是:
for (var i = 0; i < animals_data.category.length; i++) {
var currentIteration = animals_data.category[i];
var currentClass = currentIteration.class;
animals_array.push(currentClass);
};
当我运行代码时,错误说明:无法读取未定义的属性“firstIndex”。谢谢你的帮助。
编辑:包含我正在使用的实际对象。我省略了一些部分,但基本上,这就是要点。我想要放在一个新数组中的值是“class”属性中的值。
答案 0 :(得分:0)
解决了它。谢谢Xotic750指出这个错误。我的问题是:
我用的时候:
for (var i = 0; i < obj.firstKey.length; i++); {
var currentIteration = obj.firstKey[i];
var currentIndex = currentIteration.firstIndex;
new_array.push(currentIndex);
};
阵列加倍(即每个阵列加两个)。
然而当我用
替换它时new_array.push(obj.firstKey[i].firstIndex;
它运行正常。我可以知道为什么会有这样的差异吗?谢谢。
答案 1 :(得分:0)
必须清理提供的数据结构和任何列表结构
那些成员只需要从一种类型/形式转变为另一种类型/形式,
由map
最佳处理。
var
animalData = {
categories: [{
class : "Reptiles",
animals : [{
image1 : "some image",
image2 : "some image 2",
name : "Snake",
description : "some description"
}, {
image1 : "another image",
image2 : "another image 2",
name : "Crocodilia",
description : "another description"
}]
}, {
class : "Mammals",
animals : [{
image1 : "more image",
image2 : "more image 2",
name : "Cat",
description : "more description"
}, {
image1 : "image",
image2 : "image 2",
name : "Dog",
description : "long description"
}]
}, {
class : "Birds",
animals : [{
image1 : "bird image",
image2 : "bird image 2",
name : "American flamingo",
description : "bird description"
}, {
image1 : "another bird image",
image2 : "another bird image 2",
name : "Atlantic puffin",
description : "another bird description"
}]
}]
},
animalClassNameList = animalData.categories.map(function (category) {
return category.class;
});
console.log("animalData : ", animalData);
console.log("animalClassNameList : ", animalClassNameList);