简体   繁体   English

在Javascript中向数组添加元素

[英]add an element to array in Javascript

I am posting this question after I have done some search over stackoverflow for similar question but not able to find one. 我在stackoverflow上完成了针对类似问题的搜索后,但无法找到该问题,我将发布此问题。

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

Expected Output: 预期产量:

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

I used forEach loop and tried to .push() or .concat() to an element of the loop, but getting an error "concat is not a function" and "pushis not a function" 我使用了forEach循环,并尝试将.push()或.concat()设置为循环的元素,但收到错误消息“ concat不是函数”和“ pushis不是函数”

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

constant y is wrong according to javascript. 根据javascript,常数y是错误的。 First of all, please make it an array like below. 首先,请使其成为如下所示的数组。

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

const x =  {country: 'Sweden'};

Then, 然后,

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

You may use Object.assign() method: 您可以使用Object.assign()方法:

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

Demo: 演示:

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

Alternatively you can use spread syntax: 另外,您可以使用传播语法:

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

Demo: 演示:

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

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM