【发布时间】:2015-02-16 18:14:21
【问题描述】:
我有一个数组,其中包含一些名为 data 的数据。
数据如下:
var data = [
{
id: 1,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'Gray',
choice_no: 1
},
{
id: 2,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'one',
choice_no: 2
},
{
id: 3,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'two',
choice_no: 2
},
{
id: 4,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'three',
choice_no: 2
},
{
id: 5,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'four',
choice_no: 2
},
{
id: 6,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'five',
choice_no: 2
},
{
id: 7,
title: 'title',
desc: 'desc',
price: 1.12,
choice1: 'Color',
choice2: 'Size',
large_picture: 'picture',
choice: 'Black',
choice_no: 1
},
];
我目前正在尝试循环通过 data 将它们分成两个单独的数组:color 和 size。
现在data 的对象并不总是具有choice1 或choice2 作为属性。 (只是稍后的旁注)
我正在检查第二个选择并这样做:
if (data[0].choice2) {
// Has 2 choices
for (var i in data) {
if (data[i].choice1.toUpperCase() == 'SIZE' && data[i].choice_no == 1) {
size[i] = {
choice: data[i].choice,
order: data[i].sort
};
} else if (data[i].choice2.toUpperCase() == 'SIZE' && data[i].choice_no == 2) {
size[i] = {
choice: data[i].choice,
order: data[i].sort
};
} else if (data[i].choice1.toUpperCase() == 'COLOR' && data[i].choice_no == 1) {
color[i] = {
choice: data[i].choice,
order: data[i].sort
};
} else if (data[i].choice2.toUpperCase() == 'COLOR' && data[i].choice_no == 2) {
color[i] = {
choice: data[i].choice,
order: data[i].sort
};
}
} // End for()
}
这种种有效。 color.length = 7,不过,它应该只等于 2。如果我像这样循环遍历它:
for ( var x in color ) {
console.log(color[x]);
}
它输出:
Object {choice: "Gray", order: 2}
Object {choice: "Black", order: 1}
但是,如果我将循环更改为 var x = 0; x < color.length; x++,它将循环通过 0-6,并且“灰色”和“黑色”之间的所有内容都是 undefined。现在我将只使用第一个循环,因为它“有效”,但ngRepeat 的工作方式类似于第二个数组。它遍历所有 7 条记录。
TL;DR
我很确定我在我的 if 块上的某个地方搞砸了,试图将 choice1 和 choice2 分成适当的数组(颜色和大小)。
重要要注意choice1 将不始终是颜色(choice1 可能是大小),甚至可能没有任何选择。此外,我对如何修改数据非常有限。
【问题讨论】:
标签: javascript jquery arrays angularjs