[英]How to push into an array of object using the spread operator to a specific element
[英]Push an object into the array using spread operator?
我有一個這樣的對象數組,
let array1 = [{id:1,name:'One'}]
每當我進行api調用時,對象數組都會像這樣更新
let array2 = [{id:1,name:'One'}, {id:2, name:'Two'}]
第三次,會是這樣,
let array3 = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]
現在我試圖為數組中的每個對象添加鍵值對,如下所示:
obj = {
key: 'value'
}
[...array1, obj]
正在獲得類似[{id:1,name:'One'},{key: 'value'}]
但預期的輸出為[{id:1,name:'One',key: 'value'}]
該對象應在每次api調用后被推入數組
如果要將鍵值對添加到數組中的每個對象,則除了使用擴展語法外,還需要映射到數組
let array1 = [{id:1,name:'One'}] const obj = { key: 'value' } array1 = array1.map(val => ({...val, ...obj})) console.log(array1);
如果希望所有數組項都與對象合並,則可以嘗試使用Array.prototype.map()
和Object.assign()
,如下所示:
let array3 = [{id:1,name:'One'}, {id:2, name:'Two'}, {id:3, name: 'Three'}]; let obj = {key: 'value'}; let res = array3.map(i => Object.assign(i, obj)); console.log(res);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.