簡體   English   中英

Javascript在Object中添加項目

[英]Javascript add item in Object

這是我的代碼

    var arr = [{
      id: '1',
      total: "Total:",
      titlea: 'a',
      titleb: 'b',
   }];

    let c=  {titlec: 'c'}
    arr.push(c);
    console.log(arr)

所以console.log顯示了這一點

0: {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b"}
1: {titlec: "c"}

但我想要它:

0: {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b", titlec: "c"}

我怎樣才能做到這一點? 謝謝

使用.forEach().map()迭代數據集,並使用Object.assign()c對象的屬性添加到數組中的對象。

 let arr = [{ id: '1', total: "Total:", titlea: 'a', titleb: 'b', }]; let c = {titlec: 'c'} arr.forEach(o => Object.assign(o, c)); console.log(arr); 

arr.push(c); 將一個新元素推送到object.Instead使用數組mapObject.assign .Array map將返回一個新數組並具有更新的對象值

 var arr = [{ id: '1', total: "Total:", titlea: 'a', titleb: 'b', }]; let c = { titlec: 'c' } let m = arr.map(function(item) { return Object.assign(item, c) }) console.log(m) 

push()會向數組添加一個新元素,你不應該使用它

  var arr = [{ id: '1', total: "Total:", titlea: 'a', titleb: 'b', }]; let c= {titlec: 'c'} for(var i in c){ arr[0][i]=c[i]; } console.log(arr) 

let key = Object.keys(c)[0];
let value = c.titlec;
arr[0][key] = value;

嘗試這個

var arr = [{
          id: '1',
          total: "Total:",
          titlea: 'a',
          titleb: 'b',
       }];

    arr[0]["titlec"] = "c";
    console.log(arr)

如果只需要一次性使用該條件,您可以使用下面的簡單代碼,它可以正常工作,而無需使用任何循環語句。 arr[0]['titlec'] = c.titlec

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM