在提供给 Object.assign 的对象中使用变量作为键

Using variables as keys in Object supplied to Object.assign

我正在使用 Object.assign 获取对象的新副本,其中添加了来自另一张地图的属性。这通常和 Object.assign(existingObject, {"new_key", "new_value"}) 一样简单,但是当 "new_key" 以变量的形式出现时,我必须使用临时变量.如何避免这种情况?

一个简单的例子:

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

任何关于如何避免临时 newData 变量的技巧将不胜感激!

(我在 Redux 中经常使用 reducers,这对于复制对象而不是改变它们很有用。)

您可以在 ES2015 中使用 computed property names:

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

如果用方括号将变量括起来,则可以强制将其用作对象文字中的键:

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

您已经在创建一个新对象数据,无需再创建一个。

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

    data[inputKey] = inputValue;

    return data;
}