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.

2

3 Answers 3

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

1 Comment

Object.assign(myObj, {a, b, c}); inside of myFunc did it for me! Wish it was prettier though.
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.

2 Comments

In every new ES6 syntax (like class or modules), with is strictly prohibited. For good reason.
Thanks, Leland. I'd like to avoid usage of with if possible.
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 };

2 Comments

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

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.