javascript - 如何创建一个 {key :value} object from two variables?

标签 javascript dictionary ecmascript-6

我想创建一个 {key:value} 类型的对象其中键名是可变的。此类对象必须提供给 chrome.storage.<storageType>.set(keys, function(){...})

SO 上有很多相关问题并提供有效答案,但我无法找到该问题的合适解释。它归结为在 JSON 对象上设置属性。我做了这个测试:

var desiredKey = "123",
    desiredValue = "Value for key 123",
    foo;

// 1-The basic: Using a literal
console.log({ "123": desiredValue });

// 2-The problem occurs when the key name is not a literal
console.log({ desiredKey: desiredValue });

// 3-The solution is to assign a key explicitely
foo = {};
foo[desiredKey] = desiredValue;
console.log(foo);

结果:

Object { 123: "Value for key 123" }          <-- Literal
Object { desiredKey: "Value for key 123" }   <-- Variable (wrong)
Object { 123: "Value for key 123" }          <-- Assignment (ok)

问题:

  • 为什么方法 2 失败?存储了什么? desiredKey 的引用/地址?
  • 方法 3 是最简单的吗?或者有一个单一指令的解决方案吗?

最佳答案

方法4

Computed property :

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already.

var desiredKey = "123",
    desiredValue = "Value for key 123",
    foo = { [desiredKey]: desiredValue };

console.log(foo);

关于javascript - 如何创建一个 {key :value} object from two variables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39932613/

相关文章:

python - 使用字典理解将函数应用于每个键的特定子键

javascript - EcmaScript-6 向后兼容性

javascript - jquery如何加载所有元素

javascript - 使用复杂对象上的挖空功能手动设置选择框的默认值

javascript - ES6 : Why Symbol can not have another symbol as description?

javascript - 强制在 Android/iOS 应用程序中打开 Youtube 链接

python - 如何从字符串形成字典?

python - 将两个字典中的值组合成一个列表

javascript - 有时未设置内联样式的 background-position-x 或 y 属性

javascript - 将普通函数转换为箭头函数