Javascript在Object中添加项目

问题描述 投票:2回答:6

这是我的代码

    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"}

我怎样才能做到这一点?谢谢

javascript arrays object
6个回答
3
投票

使用.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);

1
投票

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)

1
投票

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)

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

1
投票

试试这个

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

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

0
投票

如果只需要一次性使用该条件,您可以使用下面的简单代码,它可以正常工作,而无需使用任何循环语句。 arr[0]['titlec'] = c.titlec

© www.soinside.com 2019 - 2024. All rights reserved.