如何在Javascript中将JSON对象转换为JSON数组

时间:2017-12-21 20:28:46

标签: javascript json

我想转换此JSON对象

{"target":{"Start":"2017-08-01","End":"2017-09-01"},"datapoints":[{"UsageQuantity":{"Amount":"6","Unit":"Hrs"}}]}
{"target":{"Start":"2017-09-01","End":"2017-09-01"},"datapoints":[{"UsageQuantity":{"Amount":"8","Unit":"Hrs"}}]}

以下列方式访问JSON数组,仅采用开始日期

[{"target": "Yearly", "datapoints": [[6, 2017-08-01], [8, 2017-09-01]]}]

2 个答案:

答案 0 :(得分:0)

您可以尝试将对象分配给数组变量,然后对数组变量进行字符串化。类似的东西:

var createArray = [var1, var2, var3];
var yourArray = JSON.stringify(createArray);
console.log(yourArray);

我相信yourArray就是你想要的

答案 1 :(得分:0)

这不是最干净的代码,它没有考虑var origin = [ { "target": {"Start":"2017-08-01","End":"2017-09-01"}, "datapoints":[ { "UsageQuantity": {"Amount":"6","Unit":"Hrs"} } ] }, { "target":{ "Start":"2017-09-01","End":"2017-09-01"}, "datapoints":[ { "UsageQuantity":{"Amount":"8","Unit":"Hrs"} } ] } ] var output = { target: "Yearly", datapoints: origin.map((item) => [item.datapoints[0].UsageQuantity.Amount, item.target.Start]) } console.log(output);可能有多个条目,但它提供了您正在寻找的数据格式。

{{1}}