I wanted to add a key:value parameter to all the objects in an array.
eg:
var arrOfObj = [{name: \'eve\'},{name:\'john\'},{name:\'jane\'}];
<
Looping through the array and inserting a key, value pair is about your best solution. You could use the 'map' function but it is just a matter of preference.
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
arrOfObj.map(function (obj) {
obj.isActive = true;
});
Simply use map function:
var arrOfObj = arrOfObj.map(function(element){
element.active = true;
return element;
}
Map is pretty decent on compatibility: you can be reasonably safe from IE <= 9.
However, if you are 100% sure your users will use ES6 Compatible browser, you can shorten that function with arrow functions, as @Sergey Panfilov has suggested.
Simply you can add that way. see below the console image
You may also try this:
arrOfObj.forEach(function(item){item.isActive = true;});
console.log(arrOfObj);
@Redu's solution is a good solution
arrOfObj.map(o => o.isActive = true;) but Array.map still counts as looping through all items.
if you absolutely don't want to have any looping here's a dirty hack :
Object.defineProperty(Object.prototype, "isActive",{
value: true,
writable: true,
configurable: true,
enumerable: true
});
my advice is not to use it carefully though, it will patch absolutely all javascript Objects (Date, Array, Number, String or any other that inherit Object ) which is really bad practice...
You can do this with map()
var arrOfObj = [{
name: 'eve'
}, {
name: 'john'
}, {
name: 'jane'
}];
var result = arrOfObj.map(function(o) {
o.isActive = true;
return o;
})
console.log(result)
If you want to keep original array you can clone objects with Object.assign()
var arrOfObj = [{
name: 'eve'
}, {
name: 'john'
}, {
name: 'jane'
}];
var result = arrOfObj.map(function(el) {
var o = Object.assign({}, el);
o.isActive = true;
return o;
})
console.log(arrOfObj);
console.log(result);