简体   繁体   English

JavaScript-通过数组中的ID查找对象并进行修改

[英]JavaScript - find an object by ID in array and modify

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 property selected : true to it #id 4345345345的数组中查找对象,添加selected : true属性selected : true
  • Then within this object with #id 4345345345 , find cat with #id 2 , add property selected : true to it 然后在具有#id 4345345345对象中,找到具有#id 2猫,添加selected : true属性selected : true


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)? 下面的作品,但是我的数组应该有1000多个对象,这感觉有点浪费,您能否建议使用任何更清洁/巧妙的解决方案(可能使用下划线)?

 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; } }; } }; 

Here are a few approaches I can think of 这是我能想到的几种方法

1) change your data structure to use the id's as the key. 1)更改数据结构,以使用ID作为键。 ie. 即。

4345345345 : cat: { 1 :{ cat: "test1" }, 2 : { cat: "test2" }} 4345345345:cat:{1:{cat:“ test1”}},2:{cat:“ test2”}}

2) Alternatively you can create a temporary lookup table based on the id to directly look the object actual objects; 2)或者,您可以基于id创建一个临时查找表,以直接查找对象的实际对象; obviously you would only create the look up table one time, or whenever the data changes. 显然,您只会一次创建一次查找表,或者每当数据更改时才创建查找表。 This will bring your runtime from O(n) to O(1). 这将使您的运行时间从O(n)变为O(1)。

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

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