0

I tried this but it only set the value to obj1

let obj1, obj2, obj3, obj4, ..., objn = {} // only obj1 is set, the rest is undefined.

I looked at this post: assign multiple variables to the same value in Javascript and they suggested this:

let obj1 = obj2 = obj3 = obj4 = ... = objn = {}

But the above says that any change in obj1 will affect obj2, obj3, ...

Is is possible to initialize all obj as {} at once without a for loop ?

TSR
  • 17,242
  • 27
  • 93
  • 197

6 Answers6

1

Using array destructuring assignment, you can use map/reduce to create objects, but neither will be as fast as a for-like loop.

let [o1,o2,o3] = Array(3).fill().map(()=>({}))

o1.id = '1'
o2.id = '2'
o3.id = '3'

console.log(o1)
console.log(o2)
console.log(o3)
vol7ron
  • 40,809
  • 21
  • 119
  • 172
0

You can use Object.assign, this function come with ES6 syntax, you can check the documentation : Object.assign

const [obj1, obj2, obj3] = [{id: 1}, {id: 2}, {id: 3}];
Object.assign(this, {obj1, obj2, obj3});
KolaCaine
  • 2,037
  • 5
  • 19
  • 31
0

var [obj, obj2, obj3] = [{"a":1},{"a":2},{"a":3}];

console.log(obj);
console.log(obj2);
console.log(obj3);

This seems to work.

sascha10000
  • 1,245
  • 1
  • 10
  • 22
0

let  {obj1, obj2, obj3 }= {obj1:{}, obj2:{}, obj3:{}};

obj1.id =10;
obj2.id =20;
obj3.id =30;

console.log("obj1",obj1);
console.log("obj2",obj2);
console.log("obj3",obj3);
Mohammed Ashfaq
  • 3,353
  • 2
  • 15
  • 22
0

Here's an interesting way to initialize an arbitrary amount of objects without explicitly initializing an array of values. This answer is very similar to Vol7ron's answer except that this uses a generator function to lazily iterate values without a pre-allocated array. The iterator returned by initialize() will only iterate as far as the destructuring assignment requires, so make sure to not use a ... rest parameter in your destructuring assignment or your iterator will never terminate.

function * initialize (fn) { while (true) { yield fn() } }

const [obj1, obj2, obj3, obj4, obj5, obj6] = initialize(() => ({}))

// all initialized
console.log(obj1, obj2, obj3, obj4, obj5, obj6)
// all unique
console.log(new Set([obj1, obj2, obj3, obj4, obj5, obj6]).size)
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
0
function declareMultipleObjects(...args){
    var arrayOfObjects = []
    args.forEach(function(each){
        each = new Object();
        arrayOfObjects.push(each);
    })

    alert(arrayOfObjects);}

declareMultipleObjects("obj1", "obj2", "obj3");
Gilbert Cut
  • 113
  • 1
  • 12
  • While this may answer the question it's better to add some description on how this answer may help to solve the issue. Please read [_How do I write a good answer_](https://stackoverflow.com/help/how-to-answer) to know more. – Roshana Pitigala Sep 22 '18 at 11:43