var arr= [{name:'xyz'},{name:'abc'}];
arr.forEach(function(a){
a.age = 25;
a.country = 'USA'
a.technology = 'JavaScript'
});
How can I add these dynamic key-value pair with spread operator using ES6 syntax
var arr= [{name:'xyz'},{name:'abc'}];
arr.forEach(function(a){
a.age = 25;
a.country = 'USA'
a.technology = 'JavaScript'
});
How can I add these dynamic key-value pair with spread operator using ES6 syntax
arr = arr.map(prev => ({ ...prev, age: 25, country:"USA" }));
map is a foreach loopI don't think you can use spread syntax to modify an object, only to create a new object. If you want something that allows you to use a Javascript object literal to modify, use Object.assign()
arr.forEach(a => Object.assign(a, {
age: 25,
country: 'USA',
technology: 'Javascript'
}));
Simply use this code:
var arr= [{name:'xyz'},{name:'abc'}];
var obj = {
age: 25,
country: 'USA',
technology: 'JavaScript'
};
arr.forEach(function(a){
Object.assign(a, obj);
});
console.log(arr);