如何在字符串文字中传递字符串数组?

时间:2018-09-20 05:10:38

标签: javascript arrays angular highcharts ecmascript-6

我在字符串文字中有一个json对象

chartOptionsStr = `{
    "chart": {
      "type": "line"
    },
    "title": {
      "text": ""
    },
    "subtitle": {
      "text": ""
    },
    "xAxis": {
      "categories": ${categories},
      "labels": {
        "align":"right",
        "rotation":"0"
    }
    },
    "yAxis": {
      "title": {
        "text": "Number of Messages"
      },
    "tickInterval": 5
    },
    "plotOptions": {
      "line": {
        "dataLabels": {
          "enabled": false
        },
        "enableMouseTracking": true
      }
    },
    "series": [{
      "name": "Sent",
      "data": [37.0, 26.9, 30.5, 47.5]
    }, {
      "name": "Delivered",
      "data": [27.0, 16.9, 20.5, 37.5]
    }, {
      "name": "Open",
      "data": [27.0, 16.9, 20.5, 37.5]
    }]
  }`;

在这个对象中,我需要传递一个数组类别

["19.Dec","12.Jan","15.Feb","28 Mar"]  as a dynamic value using ${categories}

但是问题是,当我控制台此 chartOptionsStr 时,其输出如下所示:

{
    "chart": {
      "type": "line"
    },
    "title": {
      "text": ""
    },
    "subtitle": {
      "text": ""
    },
    "xAxis": {
      "categories": 12.Dec,18.Dec,20.Dec,1.Jan,
      "labels": {
        "align":"right",
        "rotation":"0"
    }
    },
    "yAxis": {
      "title": {
        "text": "Number of Messages"
      },
    "tickInterval": 5
    },
    "plotOptions": {
      "line": {
        "dataLabels": {
          "enabled": false
        },
        "enableMouseTracking": true
      }
    },
    "series": [{
      "name": "Sent",
      "data": [37.0, 26.9, 30.5, 47.5]
    }, {
      "name": "Delivered",
      "data": [27.0, 16.9, 20.5, 37.5]
    }, {
      "name": "Open",
      "data": [27.0, 16.9, 20.5, 37.5]
    }]
  }

字符串数组被附加为单个值。

有人对此有解决方案吗?

我正在尝试从角度服务中获取高价图表的类别。因此,该值是动态的。

2 个答案:

答案 0 :(得分:0)

为什么要使JSON成为字符串?

您应该将JSON创建为普通对象;

chartOptionsJson = {
  "chart": {
    "type": "line"
  },
  "title": {
    "text": ""
  },
  "subtitle": {
    "text": ""
  },
  "xAxis": {
    "categories": categories,
    "labels": {
      "align":"right",
      "rotation":"0"
  }
  },
  "yAxis": {
    "title": {
      "text": "Number of Messages"
    },
  "tickInterval": 5
  },
  "plotOptions": {
    "line": {
      "dataLabels": {
        "enabled": false
      },
      "enableMouseTracking": true
    }
  },
  "series": [{
    "name": "Sent",
    "data": [37.0, 26.9, 30.5, 47.5]
  }, {
    "name": "Delivered",
    "data": [27.0, 16.9, 20.5, 37.5]
  }, {
    "name": "Open",
    "data": [27.0, 16.9, 20.5, 37.5]
  }]
};

然后,在注入数组时,无需将category变量包装为${categories},而只需将变量直接传递给对象即可。

答案 1 :(得分:-2)

如果您决定实施此行为,则可以使用:

const categoriesStr = `["${categories.join('", "')}"]`;
...
"xAxis": {
  "categories": ${categoriesStr},
   ...
}
相关问题