So, I spent way to many hours figuring this problem out. So basically, I have this for loop, which should add all the unique elements to a separate array.
var categories = [];
var category = {
"name": "",
"id": "",
"icon": "",
"subcategory": []
};
for (var i = 0; i < array.length; i++) {
var add = false;
for (var j = 0; j <= categories.length; j++) {
if (!objectExists(categories, array[i].zones[0].description)) {
add = true;
}
}
if (add) {
category.name = array[i].zones[0].description;
category.id = generateUUID();
category.icon = array[i].zones[0].description;
category.subcategory = [];
categories.push(category);
}
}
var objectExists = function (array, name) {
for (var i = 0; i < array.length; i++) {
if (array[i].name === name) {
return true;
}
}
return false;
};
This does not work, since the object category
will never change the different properties, they will remain the same (at least in my case). If I create the variable category
inside the if (add) { ... }
this way:
if (add) {
category = {
"name": "",
"id": "",
"icon": "",
"subcategory": []
};
category.name = array[i].zones[0].description;
category.id = generateUUID();
category.icon = array[i].zones[0].description;
category.subcategory = [];
categories.push(category);
}
It works. Can someone explain to me what happens? I've been trying to read some literature about it, but cant find anything that fits this case.
Here's a fiddle displaying what I'm experiencing. http://jsfiddle.net/fAypL/1/