在JS中将JSON更改为以下格式

时间:2018-08-22 05:52:31

标签: javascript arrays json

如何在javascript中更改以下格式的JSON

data = [{acquired: "2018-03-09T22:49:52.935Z", mean_ndvi: -0.0483685}
{acquired: "2018-02-13T22:49:16.568Z", mean_ndvi: 0.00595065}
{acquired: "2018-04-01T22:50:30.912Z", mean_ndvi: -0.033455}]

准确

data = {"2018-03-09T22:49:52.935Z":-0.0483685, "2018-02-13T22:49:16.568Z": 0.00595065, "2018-04-01T22:50:30.912Z": -0.033455}

我的尝试。

var json =data; var obj2 ={}; var obj3 =[]; 
for(var i = 0; i < json.length; i++) 
{ var obj = json[i]; 
obj2 = {[obj.acquired]:obj.mean_ndvi};
obj3.push(obj2); } 
console.log(obj3);

我可以以下格式获取它。

 {2018-04-01T22:50:30.912Z: -0.033455}, 
 {2018-04-01T22:50:30.912Z: -0.033455}, 
 {2018-04-01T22:50:30.912Z: -0.033455}

请检查可以进行哪些更改以将结果显示在一行中。

1 个答案:

答案 0 :(得分:0)

您可以按以下方式使用reduce()(其中混入一些destructuringspreading):

data.reduce((a, {acquired, mean_ndvi}) => ({[acquired]: mean_ndvi, ...a}), {});

完整摘要:

const data = [
    {acquired: "2018-03-09T22:49:52.935Z", mean_ndvi: -0.0483685},
    {acquired: "2018-02-13T22:49:16.568Z", mean_ndvi: 0.00595065},
    {acquired: "2018-04-01T22:50:30.912Z", mean_ndvi: -0.033455}
];

const result = data.reduce((a, {acquired, mean_ndvi}) => ({[acquired]: mean_ndvi, ...a}), {});

console.log(result);