向 Javascript 中的数组添加一个元素

add an element to array in Javascript

我在 Whosebug 上搜索了一些类似的问题但找不到之后,我发布了这个问题。

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 is not a function" 和 "pushis not a function"

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

常量 y 根据 javascript 是错误的。首先,请将其制成如下数组。

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);  
 });

您可以使用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; }

参考文献: