【问题标题】:Want to split one single JSON objects to multiple JSON objects using Javascript想要使用 Javascript 将一个 JSON 对象拆分为多个 JSON 对象
【发布时间】:2016-09-05 12:07:25
【问题描述】:

我有如下 JSON 响应,

[{label: "8", value: "1", value2: "0", value3: "0"},{label: "9", value: "7", value2: "2", value3: "6"},{label: "10", value: "12", value2: "1", value3: "0"},…]

现在我想为每个键将其拆分为 4 个 JSON 对象,如下所示。

[{label: "8"},{label: "9"},{label: "10"},…]
[{value: "1"},{value: "7"},{value: "12"},…] 
[{value2: "0"},{value2: "2"},{value2: "1"},…] and more

我尝试了以下方法,但没有成功。

尝试1:

var o2 = { uhash: o.uhash };
delete o.uhash;

尝试2:

使用for循环获取每一对,array.push和JSON.stringigy()方法。

我只想使用来自数据库的 JSON 响应创建一个堆叠的融合图

【问题讨论】:

标签: javascript jquery json fusioncharts


【解决方案1】:

你可以创建一个函数来返回你想要的数组: 然后,您可以映射并在 JSON 中的属性上调用它:

function makeArray(value) {
  return j.map(function(a) {
    return {[value]: a[value]};
  });
}

var labels = makeArray('label');

Working Example

【讨论】:

    【解决方案2】:

    你可以像这样使用reduce并返回数组

    var data = [{label: "8", value: "1", value2: "0", value3: "0"},{label: "9", value: "7", value2: "2", value3: "6"},{label: "10", value: "12", value2: "1", value3: "0"}]
    
    var result = data.reduce(function(ar, e) {
      ar[0] = (ar[0] || []).concat({label: e.label});
      ar[1] = (ar[1] || []).concat({value: e.value});
      ar[2] = (ar[2] || []).concat({value2: e.value2});
      ar[3] = (ar[3] || []).concat({value3: e.value3});
      return ar;
    }, [])
    
    console.log(result)

    你也可以返回对象

    var data = [{label: "8", value: "1", value2: "0", value3: "0"},{label: "9", value: "7", value2: "2", value3: "6"},{label: "10", value: "12", value2: "1", value3: "0"}],
        keys = Object.keys(data[0]);
    
    var result = data.reduce(function(ar, e) {
      ar[keys[0]] = (ar[keys[0]] || []).concat({label: e.label});
      ar[keys[1]] = (ar[keys[1]] || []).concat({value: e.value})
      ar[keys[2]] = (ar[keys[2]] || []).concat({value2: e.value2})
      ar[keys[3]] = (ar[keys[3]] || []).concat({value3: e.value3})
      return ar;
    }, {})
    
    console.log(result)

    【讨论】:

      【解决方案3】:

      为什么我不使用 Array.prototype.map 或 Object.keys,因为在 IE8 中,这些方法不起作用。要使它们工作,需要在代码中添加 Pollyfill。所以这是你不使用它们的解决方案

      var yourData = [
            { "label": "8", "value": "1", "value2": "0", "value3": "0" },
            { "label": "9", "value": "7", "value2": "2", "value3": "6" },
            { "label": "10", "value": "12", "value2": "1", "value3": "0" }
          ];
      
      var convertData = function(data) {
        var newData = [],
            dataLnth = data.length;
      
        //dynamically creating the array depending on arraySize
        for(var i = 0; i<=dataLnth; i++)
          newData.push([]);
      
        //create the data
        for(var index=0; index<dataLnth; index++) {
          var counter = 1;
          for(var key in data[index]) {
            if(key === "label")
              newData[0].push({"label" : data[index][key]});
            else
              newData[counter++].push({"value" : data[index][key]});
          }
        }
      
        return newData;
      };
      
      //printing the output in the console
      console.log(JSON.stringify(convertData(yourData)));
      

      【讨论】:

        【解决方案4】:

        您可以使用Array#forEach() 并在其中构建具有所需属性的新对象。

        var array = [{ label: "8", value: "1", value2: "0", value3: "0" }, { label: "9", value: "7", value2: "2", value3: "6" }, { label: "10", value: "12", value2: "1", value3: "0" }],
            keys = ['label', 'value', 'value2', 'value3'],
            grouped = {};
        
        array.forEach(function (a) {
            keys.forEach(function (k) {
                var o = {};
                o[k] = a[k];
                grouped[k] = grouped[k] || [];
                grouped[k].push(o);
            });
        });
        
        document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');

        【讨论】:

          【解决方案5】:

          我喜欢这里的 map() 和 getOwnPropertyNames() 虽然其他答案可能一样好。

          var data = [
            { "label": "8", "value": "1", "value2": "0", "value3": "0" },
            { "label": "9", "value": "7", "value2": "2", "value3": "6" },
            { "label": "10", "value": "12", "value2": "1", "value3": "0" }
          ];
          
          var results = data.map(function(item) {
            var retval = [];
            Object.getOwnPropertyNames(item).forEach(function(val, idx, array) {
              retval.push({ [val]: item[val] });
            });
            return retval;
          });
          
          console.log(JSON.stringify(results));

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-10-03
            • 2018-12-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-05-20
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多