如何更改JSON格式

时间:2016-04-14 12:50:37

标签: javascript arrays json

我得到ajax响应json如下

var optgroups = [{"LAST_X_HRS":1,"AREA":"WKS-FINGER1","EQ_ID":"WKS1"},
{"LAST_X_HRS":1,"AREA":"WKS-FINGER1","EQ_ID":"WKS2"},
{"LAST_X_HRS":1,"AREA":"WKS-FINGER2","EQ_ID":"WKS3"},
{"LAST_X_HRS":1,"AREA":"WKS-FINGER2","EQ_ID":"WKS4"}]

如何将其更改为以下格式

 var optgroups = [
                          {
                              label: 'WKS-FINGER1', children: [
                                  {label: 'WKS1', value: 'WKS1',},
                                   {label: 'WKS2', value: 'WKS2',}

                              ]
                          },
                          {
                              label: 'WKS-FINGER2', children: [
                                  {label: 'WKS3', value: 'WKS3',},
                                   {label: 'WKS4', value: 'WK4',}
                              ]
                          }
                      ];

2 个答案:

答案 0 :(得分:3)

您可以使用Array#forEach()并构建新阵列。

该方法使用thisArgs作为临时对象来引用项目。



var optgroups = [{ "LAST_X_HRS": 1, "AREA": "WKS-FINGER1", "EQ_ID": "WKS1" }, { "LAST_X_HRS": 1, "AREA": "WKS-FINGER1", "EQ_ID": "WKS2" }, { "LAST_X_HRS": 1, "AREA": "WKS-FINGER2", "EQ_ID": "WKS3" }, { "LAST_X_HRS": 1, "AREA": "WKS-FINGER2", "EQ_ID": "WKS4" }],
    temp = [];

optgroups.forEach(function (a) {
    if (!this[a.AREA]) {
        this[a.AREA] = { label: a.AREA, children: [] };
        temp.push(this[a.AREA]);
    }
    this[a.AREA].children.push({ label: a.EQ_ID, value: a.EQ_ID });
}, Object.create(null));

document.write('<pre> ' + JSON.stringify(temp, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我的方法与@Nina Scholz非常相似,但是当涉及减少数组Array.prototype.reduce()时,对我来说更有意义。

var optGroups = [{"LAST_X_HRS":1,"AREA":"WKS-FINGER1","EQ_ID":"WKS1"},{"LAST_X_HRS":1,"AREA":"WKS-FINGER1","EQ_ID":"WKS2"},{"LAST_X_HRS":1,"AREA":"WKS-FINGER2","EQ_ID":"WKS3"},{"LAST_X_HRS":1,"AREA":"WKS-FINGER2","EQ_ID":"WKS4"}],
reduced = optGroups.reduce((p,c) => { var i = p.length-1;
      	                              if (!!p[i] && p[i].label == c.AREA) {
      	                                p[i].children.push({label: c.EQ_ID, value: c.EQ_ID});
      	                              } else {
      	                                p.push({label: c.AREA, children: []});
      	                                p[++i].children.push({label: c.EQ_ID, value: c.EQ_ID});
      	                                }
                                      return p; }, []);

document.write('<pre> ' + JSON.stringify(reduced, 0, 2) + '</pre>');