0

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.

11
  • should it not be results.length as that is the name of your array? Commented Apr 27, 2015 at 19:05
  • @PaulFitzgerald fixed typo. Commented Apr 27, 2015 at 19:06
  • where is the closure? what the result should be? Commented Apr 27, 2015 at 19:07
  • @webduvet : each result should have all categories but for selected categories there should be ticked = true Commented Apr 27, 2015 at 19:10
  • @charlietfl : please see fiddle result and inspect categories in each object. Commented Apr 27, 2015 at 19:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

why? indexOf() returns -1 if not found.
I never get null so I will just skip this one.
@Shreejibawa I hope I can make up my past mistake with this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.