在Javascript中向数组添加元素

时间:2018-08-15 05:16:05

标签: javascript arrays foreach concat

我在stackoverflow上进行了类似问题的搜索后发现了这个问题,但是找不到。

const x =  {country: 'Sweden'};
const y =  {{name: 'james',status:'Green'},
   { name: 'Dave', status: 'Yellow'}};

预期输出:

const z = {{name: 'james',status:'Green', country: 'Sweden'},
   { name: 'Dave', status: 'Yellow', country: 'Sweden'}};

我使用了forEach循环,并尝试将.push()或.concat()设置为循环的元素,但收到错误消息“ concat不是函数”和“ pushis不是函数”

  y.forEach(function(element) {
    x = x.concat(element); 
    console.log(x);  
  });

2 个答案:

答案 0 :(得分:2)

根据javascript,

常量y是错误的。首先,请使其如下所示。

const y =  [{name: 'james',status:'Green'},
            { name: 'Dave', status: 'Yellow'}];

const x =  {country: 'Sweden'};

然后

y.forEach(function(element) {
   element.country  = x.country; 
   console.log(x);  
 });

答案 1 :(得分:1)

您可以使用Object.assign()方法:

const z = y.map(o => Object.assign(o, x));

演示:

const x =  {country: 'Sweden'};
const y =  [
  {name: 'james',status:'Green'},
  {name: 'Dave', status: 'Yellow'}
];

const z = y.map(o => Object.assign(o, x));

console.log(z);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或者,您可以使用传播语法:

const z = y.map(o => ({...o, ...x}));

演示:

const x =  {country: 'Sweden'};
const y =  [
  {name: 'james',status:'Green'},
  {name: 'Dave', status: 'Yellow'}
];

const z = y.map(o => ({...o, ...x}));

console.log(z);
.as-console-wrapper { max-height: 100% !important; top: 0; }

参考: