Muhammad Umer
Muhammad Umer

Reputation: 18097

Assign multiple values to an object in one go as with variable assignment in JavaScript

It is possible to do:

let a = 1,
    b = 3,
    c = 9;

Is it also possible to do:

obj.a = 1,
    b = 2,
    c = 3;

This is still very readable, but a lot less typing, then writing obj a lot of times.

Upvotes: 2

Views: 2437

Answers (5)

Muhammad Usman
Muhammad Usman

Reputation: 478

You can do this (if object is re-assignable ex: let NOT const ):

obj = {...obj, a : 1,
    b : 2,
    c: 3,
}

Thank you :)

Upvotes: 0

user2314737
user2314737

Reputation: 29307

If there exists a relation between the property names and the values then one can write a compact object definition using map. Otherwise one can just initialize the object with names and values.

// function
var obj = {};
['a', 'b', 'c'].map((x, i) => (obj[x] = i));
console.log(obj);

// no function
var obj1 = {a: 1, b: 2, c: 4};
console.log(obj1);

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can assign the defined variables using shorthand property names

let a = 1,
    b = 3,
    c = 9;

let  obj = {a,b,c}
    
console.log(obj)

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

If the variables are not already assigned, you could use Object.assign:

const obj = Object.assign({}, { a: 1, b: 2, c: 3 });
console.log(obj);

Otherwise, use ES6 shorthand property notation:

const [a, b, c] = [1, 2, 3];
const obj = { a, b, c };
console.log(obj);

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370639

If the variables are already defined, you can use shorthand property names to define the object in one go, without any repetition:

const obj = { a, b, c };

Upvotes: 1

Related Questions