【发布时间】:2017-01-15 10:18:30
【问题描述】:
我有一个这样的对象:
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”。感谢您的帮助。
编辑:包括我正在使用的实际对象。我省略了一些部分,但基本上,这就是要点。我要放入新数组的值是“类”属性中的值。
【问题讨论】:
-
您的对象字面量有问题。请构建一个工作示例。
-
当前代码产生
Uncaught SyntaxError: Unexpected token ] -
在
for语句的末尾删除;:i++)和{之间应该只有空格。就目前而言,您会立即完成循环。 -
编辑它以包含我正在使用的对象。
-
您的示例仍然无法重现。
Uncaught ReferenceError: obj is not defined
标签: javascript arrays data-structures mapping javascript-objects