Please note that the following scenario is for the demonstration purposes only.
Lets assume I have a following array of object:
var obj = [{
id: 4345345345,
cat: [{
id: 1,
cat: "test1"
}, {
id: 2,
cat: "test2"
}]
}, {
id: 3453453421,
cat: [{
id: 1,
}, {
id: 2,
}]
}];
My goal is to :
- Find an object within an array with
#id 4345345345, add propertyselected : trueto it - Then within this object with
#id 4345345345, find cat with#id 2, add propertyselected : trueto it
The below works, however should my array have 1000+ objects it's feels somehow wasteful, can you please suggest any cleaner/clever solution ( possible using underscore)?
for (var i = 0; i < obj.length; i++) {
var parent = obj[i];
if (parent.id === 4345345345) {
parent.selected = true;
for (var j = 0; j < parent.cat.length; j++) {
var sub = parent.cat[j];
if(sub.id === 2) {
sub.selected = true;
}
};
}
};
idmatches a specific value. If you knew the array were going to be in order (e.g. the object withid122 were always the nth member of the array) you could just doobj[n]to get it instead of using the loop.