编程语言
首页 > 编程语言> > javascript-如何在json对象中使用可变定义的键?

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

作者:互联网

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

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

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

当我解析此json键“ relationshipType”时,它是文字的,而不是解析为“兄弟”的已定义变量.有任何想法吗?

如下面的输出所示,“ relationshipType没有被解析为”兄弟”.

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

标签:json,javascript,rhino
来源: https://codeday.me/bug/20191119/2036286.html