Method to add an additional property to each object in an array.

consider the array as

const data = [

{ id: 1, name: 'John', address: '123 Main St' },

{ id: 2, name: 'Jane', address: '456 Elm St' },

{ id: 3, name: 'Bob', address: '789 Oak St' }

];

we need to add additional property to each object inside the array

  1. By using map method to iterate over the array and using (...) spread operator to have a copy of the data array

Additional Property country: USA is added to the array as follows:

const newData = data.map(obj => {

?return { ...obj, country: 'USA' };

});

console.log(newData);

The Output :

[

?{ id: 1, name: 'John', address: '123 Main St', country: 'USA' },

?{ id: 2, name: 'Jane', address: '456 Elm St', country: 'USA' },

?{ id: 3, name: 'Bob', address: '789 Oak St', country: 'USA' }

]




要查看或添加评论,请登录

社区洞察

其他会员也浏览了