【发布时间】:2015-10-15 15:45:47
【问题描述】:
我有一个基本遍历类别列表的 for 循环。每个类别(字符串)有 4 个不同的项目,可以是真或假。以下是我的代码的 sn-p:
var i,
category,
items,
categories= {};
for (i = 0; i < categories.length; i++) {
category = categories[i];
items = {};
items.first = availableItems[i][0] == true;
items.second = availableItems[i][1] == true;
items.third = availableItems[i][2] == true;
items.fourth = availableItems[i][3] == true;
categories+= { category : items};
}
我想最终得到一个如下的类别对象结构:
{ category1 : {
first : true,
second : true,
third : false,
fourth : true
},
category2 : {
first : true,
second : true,
third : false,
fourth : false
},
category3 : {
first : true,
second : true,
third : false,
fourth : false
}
}
谁能告诉我我做错了什么?
【问题讨论】:
-
categories+= { category : items};真的吗?我建议使用categories作为array,然后使用push在数组中添加对象。var categories = [];和内部for使用categories.push({ category : items}); -
@Tushar - 我是 JS 新手,所以如果你能给我一个很好的例子
-
@user1809790 在他的评论中有一个例子。
-
你能解释一下这个问题吗?我不得不删除我的答案,因为我不确定你在问什么
-
@RichardHamilton 所以基本上我需要遍历多个类别,每个类别将有 4 个项目,每个项目可以是真或假。现在,我想得到一个对象,它的结构类似于 { thisIsCategory1 : { first : true, second : false, third : true, Fourth : false }, { thisIsCategory123 : { first : false, second : true, third : false , Fourth : true } } 如您所见,在循环时从类别中检索类别名称
标签: javascript object javascript-objects