[英]Stuffing an array into an object that is inside an array that matches an id
I have a server response that comes back as such: 我有这样的服务器响应:
Array[2]
0:Object
user: "Howard",
id:0
1:Object
user: "Robin",
id:1,
myArray: ["mary","john","gary"] // I want to add in here.
]
I then have an array that I created myself. 然后,我有了一个自己创建的数组。 I want to add this array to where an id that === 1 like my example above.
我想将此数组添加到ID === 1的位置,例如上面的示例。 I can only imagine I have to use the key of the object that matches id === 1
我只能想象我必须使用与id === 1匹配的对象的键
myArray=["mary","john","gary"]
Hopefully I'm not misunderstanding the question. 希望我不会误解这个问题。 just loop through the main array looking for id === 1, then access the myArray property and do what you need.
只需遍历主数组以查找id === 1,然后访问myArray属性并执行所需的操作即可。
mainArray.forEach(function(object) {
if(object.id === 1) {
object.myArray = ["mary","john","gary"];
}
}
You can use find
to find the object you want, then add the array to it like this: 您可以使用
find
查找所需的对象,然后向其添加数组,如下所示:
function addToObject(arr, id, myArr) { var obj = arr.find(function(o) { // sear inside arr for the object with the id === 1 return o.id === id; }); if(obj) // if we found an object obj.myArray = myArr; // add the array myArr as a property to it } var arr = [{user: "Howard",id:0}, {user: "Robin",id:1}]; addToObject(arr, 1, ["some", "text"]); // add the array to the object with the id 1 console.log(arr);
Note: I assumed the IDs are unique! 注意:我认为这些ID是唯一的! So for an ID
id
there will be ay most one object with that ID. 因此,对于一个ID
id
,最多只有一个具有该ID的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.