Reputation: 1379
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
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
Reputation: 37885
let obj = {};
for(let key of "xyz")
obj[key] = []
console.log(obj)
Upvotes: 2
Reputation: 68423
you can try
var obj = {};
var keys = [ "x", "y", "z" ];
keys.forEach( function( val ){
obj[ val ] = [];
});
Upvotes: 3