将数组添加到现有对象

时间:2019-12-02 12:14:05

标签: javascript arrays object

“我有一个数组:

myArray = []

我正在遍历一些数据并将其添加到我的数组中:

myArray.push(listItem)

然后,我想向该数组添加一个对象数组。最终结果是,在这些对象中的每个对象内部都是图像路径的数组

0:
id: "8okCSIfrSTugwBW4Oa0Q"
images: [{…}]
title: "My Title 1"
1:
id: "8okCSIfrSTugwBW4Oa023"
images: [{…}]
title: "My Title 2"

我尝试了以下操作:

var newIndex = index - 1;
var imagesArray = [];
imagesArray.push(imageString);
this.myArray[newIndex]["images"] = imagesArray;

1 个答案:

答案 0 :(得分:4)

只需findyourArray中的所需对象并分配所需值:

let yourArray = [];

yourArray.push({id: "8okCSIfrSTugwBW4Oa0Q", title: "My Title 1"});
yourArray.push({id: "8okCSIfrSTugwBW4Oa023", title: "My Title 2"});

yourArray.find(f=>f.id = "8okCSIfrSTugwBW4Oa0Q").images = [];

console.log(yourArray);

或更安全的版本,可以检查所需的对象是否存在:

let yourArray = [];

yourArray.push({id: "8okCSIfrSTugwBW4Oa0Q", title: "My Title 1"});
yourArray.push({id: "8okCSIfrSTugwBW4Oa023", title: "My Title 2"});

let desiredObject = yourArray.find(f=>f.id = "8okCSIfrSTugwBW4Oa0Q");
if (desiredObject)
    desiredObject.images = [];

console.log(yourArray);

更新:

如果您无权访问addImage函数中的ID,则通过索引即可:

yourArray[0].images = [];

此外,您可以通过findIndex方法找到索引:

let yourArray = [];

yourArray.push({id: "8okCSIfrSTugwBW4Oa0Q", title: "My Title 1"});
yourArray.push({id: "8okCSIfrSTugwBW4Oa023", title: "My Title 2"});


let index = yourArray.findIndex(f => f.title == 'My Title 1');
if (index != -1)
    yourArray[index].images = [];

console.log(yourArray);