[英]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 : 我的目标是:
#id 4345345345
, add property selected : true
to it #id 4345345345
的数组中查找对象,添加selected : true
属性selected : true
#id 4345345345
, find cat with #id 2
, add property selected : true
to it #id 4345345345
对象中,找到具有#id 2
猫,添加selected : true
属性selected : true
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.