Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill() method for object type

Tags:

javascript

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.

like image 713
Emad Emami Avatar asked Sep 13 '25 22:09

Emad Emami


2 Answers

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);
like image 183
ibrahim mahrir Avatar answered Sep 16 '25 12:09

ibrahim mahrir


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 )
like image 35
Slai Avatar answered Sep 16 '25 13:09

Slai