Javascript has Array.prototype.fill()
method for Arrays, but what about objects? if we have something like this:
let obj ={
a: true,
b: 'Hi Dude',
c: 12
}
is there any built-in method to fill all properties with one value and make it like this:
let obj ={
a: 'goodbye Dude',
b: 'goodbye Dude',
c: 'goodbye Dude'
}
I know forEach()
or for...in
solutions can do that, but I hope it can be done with a better approach.
There isn't one for objects because the properties of objects are not uniform (not like indexes of an array which we know goes from 0
to length - 1
).
But you can implement what you need using Object.keys
and Array#forEach
:
Object.keys(theObject).forEach(function(key) {
theObject[key] = theValue;
});
which is even shorter using an arrow function:
Object.keys(theObject).forEach(key => theObject[key] = theValue);
If by any chance the object is from JSON, the values can also be changed with JSON.parse
:
j = '{ "a": true, "b": "Hi Dude", "c": 12 }'
o = JSON.parse(j, (k, v) => k === '' ? v : 'goodbye Dude')
console.log( o )
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