1

Is there a cleaner way of setting the values a,b, and c in bar. Something similar to ES6 destructuring-assignment syntax?

bar = { foo: 10, a: 0, b: 0, c: 0, baz: 14 };

myFunc = (myObj) => {
    const { foo } = myObj;
    let a, b, c;
    a = 1 + foo;
    b = 2 + foo;
    c = 3 + foo;
    myObj.a = a;
    myObj.b = b;
    myObj.c = c;
}

myFunc(bar);

Assuming that bar has already been instantiated somewhere else, I'd like to set the new values without creating/assigning a new object to bar. We could do something like this myObj = {...myObj, a, b, c}, but that'd assign a new object to bar, from my understanding.

raychz
  • 1,085
  • 1
  • 8
  • 24
  • Given they are constants, how about `const bar = {foo: 10, a: 11, b: 12, c: 13};`? However, I think what you really are looking for are [Self-references in object literal declarations](https://stackoverflow.com/q/4616202/1048572) – Bergi Oct 30 '17 at 04:00
  • I think what you're looking for is [How to assign multiple values to a JavaScript object?](https://stackoverflow.com/questions/22109929/how-to-assign-multiple-values-to-a-javascript-object) – Tigregalis Oct 30 '17 at 04:54

3 Answers3

1

Based on this answer to a similar question, you can use Object.assign().

bar = { foo: 10, a: 0, b: 0, c: 0, baz: 14 };

myFunc = (myObj) => {
    const { foo } = myObj;
    let a, b, c;
    a = 1 + foo;
    b = 2 + foo;
    c = 3 + foo;
    Object.assign(myObj, {a: a, b: b, c: c});
}

myFunc(bar);

or of course

    const { foo } = myObj;
    Object.assign(myObj, {a: 1 + foo, b: 2 + foo, c: 3 + foo})
Tigregalis
  • 607
  • 3
  • 11
  • 1
    `Object.assign(myObj, {a, b, c});` inside of `myFunc` did it for me! Wish it was prettier though. – raychz Oct 30 '17 at 07:24
0

ES6 did not bring in any features that would make this code simpler. There is one feature available, but it is a best practice not to use it. The with keyword

with (bar) {
 a = foo+1
 b = foo+2
 c = foo+3
}

The best way to make that code shorter would be to wrap the logic into a method call if it is being re-used a lot.

yxre
  • 3,576
  • 21
  • 20
0

You can use an object literal shorthand and construct your object the other way round:

const foo = 10;
const a = 1+foo, b = 2+foo, c = 3+foo;
const bar = { foo, a, b, c };

which of course could be shortened to simply

const bar = { foo, a: 1+foo, b: 2+foo, c: 3+foo };
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • See my edit please. Let's assume `bar` has been created elsewhere. I'd like to streamline the assignments to `a`, `b`, and `c` in `bar` without creating a new object. – raychz Oct 30 '17 at 04:20
  • 1
    Well you could do `Object.assign(bar, {a,b,c})`, but I think it's even simpler to just avoid those local variables and write `bar.a = 1+foo; bar.b = 2+foo; bar.c = 3+foo;`. I don't see what would be wrong with that (of course your example is a bit repetitive, I guess you'd need to show us your actual use case). – Bergi Oct 30 '17 at 05:06