My goal is:
var arr = [{name: 'Alex'},{name: 'Mia'},{name: 'David'}];
bz(arr,'areWeAwesome','shuAr')
This should change arr to:
[{name: 'Alex', areWeAwesome: 'shuAr'},{name: 'Mia', areWeAwesome: 'shuAr'},{name: 'David', areWeAwesome: 'shuAr'}];
And I actually know how to do this:
function bz(zarr,zkey,zval) {
for(var i in zarr) {
zarr[i][zkey] = zval;
}
}
But I can't figure it out how to implement this with reduce... I just don't see it. I tried many variations, the last one is this:
function bzz(zarr,zkey,zval) {
return zarr.reduce(function(acc,val){
return acc[val[zkey] = zval]
},[{}]);
}
I read about reduce in the MDN documentation, but it didn't help... I just can't get it... would appreciate if you could help me with this
With Array#reduce and Array#concat for a new object with the wanted key/value pair.
function bz(array, key, value) {
return array.reduce((r, o) => r.concat(Object.assign({}, o, { [key]: value })), []);
}
var arr = [{name: 'Alex'},{name: 'Mia'},{name: 'David'}];
console.log(bz(arr,'areWeAwesome','shuAr'));
With Array#map, which is preferable, because it returns an array with a value for each item of the given array.
function bz(array, key, value) {
return array.map(o => Object.assign({}, o, { [key]: value }));
}
var arr = [{name: 'Alex'},{name: 'Mia'},{name: 'David'}];
console.log(bz(arr,'areWeAwesome','shuAr'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With