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

Using variables as keys in Object supplied to Object.assign

本文关键字:变量 对象 Object asassign      更新时间:2023-09-26

我正在使用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 中使用化简器做了很多工作,这对于复制对象而不是改变它们非常有用。

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

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