Reputation: 29
obj = [{name: 'Elie'},{name: 'Tim'},{name: 'Elie'}]
function addKeyAndValue(arr,key,value) {
newOne = [];
arr.forEach(function(val,i,arr){
newOne.push(arr[i].key = value);
});
return newOne;
}
I'm trying to pass an array of objects with key and value to add, like so: addKeyAndValue(obj, isItawesome, true)
and then I expect to get something like:
[{name: 'Elie', isItawesome: true},{name: 'Tim', isItawesome: true},{name: 'Elie', isItawesome: true}]
but I'm getting an error... can anyone explain why am I getting it, please?
Upvotes: 2
Views: 51
Reputation: 4615
First of all, you have to use string, as key, so call your function in that way:
addKeyAndValue(obj, 'isItawesome', true)
Secondly, you are pushing a value, not an object to your array in that place:
newOne.push(arr[i].key = value);
Change it into:
newOne.push({...val, [key]: value})
If you want to make it even better:
function addKeyAndValue(arr, key, value){
return arr.map(el => ({...el, [key]: value });
}
Upvotes: 2
Reputation: 31950
You are calling the function incorrectly. Do
addKeyAndValue(obj, 'isItawesome', true)
Note that isItawesome
is a string not a variable so you need to wrap it inside quotes
Upvotes: 1
Reputation: 3135
This should work
obj = [{name: 'Elie'},{name: 'Tim'},{name: 'Elie'}]
var result = obj.map(function(el) {
var o = Object.assign({}, el);
o.isItawesome = true;
return o;
})
console.log(result);
Upvotes: 0