How add new element to an existing object with array.map()
03 Nov 2016The map() method creates a new array with the results of calling a function for every array element.
arr.map(callback[, thisArg])
var array = [
{ end_date: '01/11/2012',
key: '101',
address: 'Felipe Villanueva',
zip: '1040',
company: 'Vendor',
start_date: '01/09/2012' },
{ end_date: '01/11/2012',
key: '102',
address: 'Felipe Villanueva',
zip: '1040',
company: 'Vendor',
start_date: '01/09/2012' },
{ end_date: '01/11/2012',
key: '103',
address: 'Felipe Villanueva',
zip: '1042',
company: 'Vendor',
start_date: '01/09/2012' }
];
//function for add new item
const newArr = array.map(function (item) {
item.status = 'new item'
return item
})
console.log(array)
Result:
var array = [
{ end_date: '01/11/2012',
key: '101',
address: 'Felipe Villanueva',
zip: '1040',
company: 'Vendor',
status : 'new item',
start_date: '01/09/2012' },
{ end_date: '01/11/2012',
key: '102',
address: 'Felipe Villanueva',
zip: '1040',
company: 'Vendor',
status : 'new item',
start_date: '01/09/2012' },
{ end_date: '01/11/2012',
key: '103',
address: 'Felipe Villanueva',
zip: '1042',
company: 'Vendor',
status : 'new item',
start_date: '01/09/2012' }
];
View console