2

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.

4
  • declaration happens way earlier, i need to assignment only Commented Apr 7, 2019 at 3:43
  • 1
    you could jump into your delorean and use with ... but that's not recommended Commented Apr 7, 2019 at 3:44
  • Object.assign(obj, { a: 1, b: 2, c: 3 }); would do it in 1 line, but just assigning 3 times in a row is not a bad thing Commented Apr 7, 2019 at 3:48
  • 2
    less typing is arguably one of those early programmer goals. Experienced programmers choose readability and editability over tersness. As proof see pretty much any major company's style guide which would tell you not to code this way. Commented Apr 7, 2019 at 4:15

5 Answers 5

1

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 };
Sign up to request clarification or add additional context in comments.

Comments

1

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)

4 Comments

this is the best so far. although double memory usage but very easy to follow
double memory usage huh?
@MuhammadUmer in most cases memory useage will not be an issue as JS uses grabage collector
true. this what i'm doing right now too. so it's good to see it's being recommended. only problem i see is i'm declaring/assigning 2x variables for same amount of data. but not a big or even medium problem.
1

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);

Comments

0

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);

Comments

0

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

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

Thank you :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.