如何在 json 对象中使用可变定义的键?

How to use variably defined keys in json object?

我正在使用犀牛。我想使用变量来定义地图的键,如下所示:

var name = "Ryan";
var relationshipType = "brother";
var relatedName = "David";

var json = {
                "name": name,
                "relationships": {
                    relationshipType: relatedName
                }
           };

当我解析这个 json 时,键 "relationshipType" 是文字而不是解析为 "brother" 的已定义变量。有什么想法吗?

"relationshipType 未被解析为 "brother",如下面的输出所示:

{
    "name": Ryan,
    "relationships": {
         relationshipType: David
    }
};

你可以像这样使用bracket notation

var name = "Ryan";
var relationshipType = "brother";
var relatedName = "David";

var json = {
  "name": name,
  "relationships": {}
};

json[relationshipType] = relatedName;

console.log(json);

如果你会用ES6语法就可以这样解决这个问题

var name = "Ryan";
var relationshipType = "brother";
var relatedName = "David";

var json = {
  "name": name,
  "relationships": {
    [relationshipType]: relatedName
  }
};

Example