简体   繁体   English

遍历js集合

[英]iterating over js collection

I use backbone & underscore js + JQuery 我使用骨干和下划线js + jQuery

I have a collection of objects, say Collection-A 我有一组对象,例如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"}] 我还有另一个收藏集,例如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 在集合A中,如果集合B中存在对象的ID,我想将标志'isReady'的值更新为true

What is the best way to do it? 最好的方法是什么?

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 我更改了数据,因为在您的示例中您没有有效的JS(在Object常量中,您必须使用:而不是= )语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM