I have an array that contains some data called, well, data.
Data looks like:
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
},
];
I am currently trying to loop through data to separate them into two separate arrays: color and size.
Now data's objects will not always have choice1 or choice2 as properties. ( Just a side note for later )
I am checking for the second choice and doing the loop as such:
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()
}
This kind of works. color.length = 7, though, when it should only equal 2. If I loop through it like:
for ( var x in color ) {
console.log(color[x]);
}
It outputs:
Object {choice: "Gray", order: 2}
Object {choice: "Black", order: 1}
But if I change the loop to var x = 0; x < color.length; x++ it loops through 0-6 and everything between "Gray" and "Black" is undefined. Now I would just use the first loop as it 'works' but ngRepeat works similar to the second array. It loops through all 7 records.
TL;DR
I'm pretty sure I messed up somewhere on my if block trying to separate choice1 and choice2 into their proper arrays ( color & size ).
It is important to note that choice1 will NOT always be color ( choice1 could be size ) and there may not even be ANY choices. Also I am very limited to how I can modify data.