简体   繁体   English

使用类似结构的语法在对象中分配多个值

[英]Assign to multiple values in object using destructure-like syntax

Is there a cleaner way of setting the values a , b , and c in bar . 有没有一种更干净的方法来设置bar abc值。 Something similar to ES6 destructuring-assignment syntax? 类似于ES6解构分配语法吗?

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 . 假设bar已经在其他地方实例化,我想设置新值而不创建新对象或将其分配给bar We could do something like this myObj = {...myObj, a, b, c} , but that'd assign a new object to bar , from my understanding. 我们可以做这样的事情myObj = {...myObj, a, b, c} ,但是根据我的理解,这会为bar指定一个新对象。

Based on this answer to a similar question , you can use Object.assign() . 基于对类似问题的回答 ,可以使用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})

ES6 did not bring in any features that would make this code simpler. ES6没有引入任何使该代码更简单的功能。 There is one feature available, but it is a best practice not to use it. 有一个可用的功能,但是最好不要使用它。 The with keyword with关键字

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. 使代码更短的最佳方法是,如果重复使用很多逻辑,则将其包装到方法调用中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM