简体   繁体   English

将数组填充到与ID匹配的数组内部的对象中

[英]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.

相关问题 mongoDB $unset 每个与数组中的 id 匹配的对象 - mongoDB $unset each object that matches id in array 将元素与另一个数组匹配的数组的过滤器对象(具有键“id”) - Filter Object of Array (having key 'id') that matches element with another array 检查一个数组是否包含一个 id 与 id 列表匹配的对象 - Check, whether an array contains an object with id that matches list of ids 排序对象数组以首先放置与 id 匹配的特定 object - sort array of objects to place a particular object first that matches an id 更新数组内的对象值,其中 id 等于数组内 - Update object values inside array where id is equal to inside Array 在数组中设置对象属性 true/false,无论 id 是否与另一个对象数组中的任何 id 匹配 - Set object property in an array true/false, whether the id matches with any id from another array of objects 如何访问Match数组中的所有Match - How to access all the matches inside matches array 根据javascript中的id删除对象内部数组中的对象 - remove object inside array inside an object based on id in javascript Javascript 对于每个 Object 在 Array 中包含一个属性是 Array 检查 If Value Matches - Javascript For Each Object inside Array containing a property that is Array check If Value Matches javascript - 如何将数组中与 id 不匹配的对象与数组中的不同对象进行比较? - How to sort object that does not match by id inside of array compare to different object inside of an array in Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM