omgj
omgj

Reputation: 1379

Efficient way to add to JS objects?

I want to add a bunch of attributes to an object, each of which is an empty array. My implementation seems verbose.

let obj = {};
obj.x = [];
obj.y = [];
obj.z = [];

... ad infinitum

Is there any other way, like reverse object de-structuring?

Upvotes: 2

Views: 97

Answers (3)

Endless
Endless

Reputation: 37885

Just another way of doing it in one line

var obj = ['x', 'y', 'z'].reduce((obj, key) => (obj[key] = [], obj), {})

Then it can be reusable

var fn = (obj, key) => (obj[key] = [], obj);
var dest = {};

var same = ['x', 'y', 'z'].reduce(fn, dest)

console.log(dest)
console.log(same === dest)

Upvotes: 0

Endless
Endless

Reputation: 37885

let obj = {};

for(let key of "xyz")
    obj[key] = []

console.log(obj)

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68423

you can try

var obj = {};
var keys = [ "x", "y", "z" ];
keys.forEach( function( val ){ 
  obj[ val ] = []; 
});

Upvotes: 3

Related Questions