Reputation: 3
I have a list of objects 'objlist' and a list of ids 'idlist'.
var objlist = [{id:1, visible:true},{id:2, visible:false},{id:3, visible:false}];
var idlist = [1, 3];
I want the objects in the first list to have value of 'visible' as 'true' for every ids in second list, and the remaining to have value 'false'.
When I try with loop within a loop, I get incorrect result. How to get the proper list.
My attempt:
var objlist = [{id:1, visible:true},{id:2, visible:false},{id:3, visible:false}];
var idlist = [1, 3];
_.each(idlist, function(p) {
_.each(objlist, function(obj) {
if (obj.id == p) {
obj.visible = true;
} else {
obj.visible = false;
}
});
});
console.log(objlist)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
What happens is when the condition breaks in subsequent loops, the values get changed.
Upvotes: 0
Views: 108
Reputation: 24945
To start with, why you code does not work:
You are looping on idList
first and then looping on objlist
. So the issue here is, on every iteration, only 1 object can have true for condition. Hence the last one is true
.
Following is a sample using underscore:
Note: Other answers have already shown approaches using vanilla JS, but since you already are using underscore, you can check this approach
var objlist = [{id:1, visible:true},{id:2, visible:false},{id:3, visible:false}];
var idlist = [1, 3];
_.each(objlist, function(p) {
p.visible = _.contains(idlist, p.id)
});
console.log(objlist)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Upvotes: 1
Reputation: 28475
Try following
var objlist = [{id:1, visible:true},{id:2, visible:false},{id:3, visible:false}];
var idlist = [1, 3];
objlist = objlist.map(function(item){
item.visible = idlist.indexOf(item.id) !== -1;
return item;
});
console.log(objlist);
Upvotes: 0
Reputation: 8761
This works.
var objlist = [{id:1, visible:true},{id:2, visible:false},{id:3, visible:false}];
var idlist = [1, 3];
for(var index in objlist)
{
var obj = objlist[index];
obj.visible = idlist.includes(obj.id);
}
console.log(objlist);
Upvotes: 0
Reputation: 13356
You can use array.prototype.map
and array.prototype.includes
:
var objlist = [{id:1, visible:true},{id:2, visible:false},{id:3, visible:false}];
var idlist = [1, 3];
var result = objlist.map(e => (e.visible = idlist.includes(e.id), e));
console.log(result);
Upvotes: 0
Reputation: 68413
Use forEach
and includes
objlist.forEach( s => (s.visible = idlist.includes( s.id ) ) );
Demo
var objlist = [{id:1, visible:true},{id:2, visible:false},{id:3, visible:false}];
var idlist = [1, 3];
objlist.forEach( s => (s.visible = idlist.includes( s.id ) ) );
console.log(objlist);
Upvotes: 0