I am adding all categories after ticking them to true if they exists in selected categories of result but it combines previous categories results with current one. I tried closure but it doesn't give me fresh object. Check out fiddle.
var allCatsResult = [{"id":1},{"id":2}, {"id":3}, ... ];
var catsArray = [1, 2] // Array of ids from allCatsResult
var result = [
{"id":1, selectedCategories:[{"id":1},{"id":2}]},
{"id":2, selectedCategories:[{"id":4},{"id":5}]},
...
];
for (var i = 0; i < results.length; i++) {
var tmp = allCatsResult; // tried to add function form here didn't work
for (var k = 0; k < results[i].selectedCategories.length; k++) {
var index = catsArray.indexOf(results[i].selectedCategories[k].category_id);
if(index !== -1) {
tmp[index].ticked = true;
}
}
results[i].categories = tmp;
}
Above code gives combined result for ticked = true for all categories in each result.
asked Apr 27, 2015 at 19:03
Shreejibawa
1,8681 gold badge28 silver badges38 bronze badges
1 Answer 1
You need to copy/clone the array of objects, or you're manipulating the original. There are a few ways apparently. I chose the following:
var tmp = JSON.parse(JSON.stringify(allCatsResult));
This will create a new array of objects in tmp, and it will correctly only modify the clone.
answered Apr 27, 2015 at 19:16
Mackan
6,2712 gold badges29 silver badges46 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
charlietfl
why?
indexOf() returns -1 if not found.Shreejibawa
I never get null so I will just skip this one.
Mackan
@Shreejibawa I hope I can make up my past mistake with this
lang-js
results.lengthas that is the name of your array?ticked = true