Arshad Rehmani
Arshad Rehmani

Reputation: 2185

iterating over js collection

I use backbone & underscore js + JQuery

I have a collection of objects, say Collection-A

[
{"id"="1" , "isReady"="false"}, 
{"id"="2" , "isReady"="false"},
{"id"="3" , "isReady"="false"},
{"id"="4" , "isReady"="false"}
]

and I have another collection, say Collection-B, [{"id"="2"}, {"id"="3"}]

In the collection-A, I want to update the value of flag 'isReady' to true if the id of object is present in the Collection-B

What is the best way to do it?

Upvotes: 1

Views: 58

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Try this

var a = [
  {id: "1", isReady: "false"}, 
  {id: "2", isReady: "false"},
  {id: "3", isReady: "false"},
  {id: "4", isReady: "false"}
];

var b   = [{id: "2"}, {id: "3"}];
var ids = _.pluck(b, 'id');

_.each(a, function (el) {
  if (_.indexOf(ids, el.id) >= 0) {
    el.isReady = true;
  }
});

console.log(a);

Example

I've change data, because in your example you have not valid JS (in Object literals you must use : instead of =) syntax

Upvotes: 1

Related Questions