简体   繁体   中英

Using variables as keys in Object supplied to Object.assign

I am using Object.assign to get a new copy of an Object with added properties from another map. This is usually as simple as Object.assign(existingObject, {"new_key", "new_value"}), but when "new_key" comes in the form of a variable I have to use a temporary variable. How to avoid this?

A simple example:

function demo(inputKey, inputValue) {
    let data = {
        "existing_key": "existing_value"
    }
    let newData = {}
    newData[inputKey] = inputValue
    return Object.assign(data, newData)
}
//demo("new_key", "new_value")
//returns Object {existing_key: "existing_value", new_key: "new_value"}

Any tricks on how to avoid the temporary newData variable would be appreciated!

(I work a lot with reducers in Redux, this having great use for copying objects instead of mutating them.)

您可以在ES2015中使用计算出的属性名称执行此操作:

return Object.assign(data, {[inputKey]: inputValue})

you can force a variable to be used as a key in object literals if you surround it with square brackets:

 function demo(inputKey, inputValue) { let data = { "existing_key": "existing_value" } let newData = {[inputKey] : inputValue} //newData[inputKey] = inputValue return Object.assign(data, newData) } console.log( demo('one',42) ) 

You are already creating a new object data , no need to create another one.

function demo(inputKey, inputValue) {
    let data = {
        "existing_key": "existing_value"
    }

    data[inputKey] = inputValue;

    return data;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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