Want to split one single JSON objects to multiple JSON objects using Javascript

我是研究僧i 提交于 2019-12-10 15:28:21

问题


I have a JSON response like below,

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

Now I want to split it into 4 JSON objects for each key, like below.

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

I tried below things but wasn't successful.

Try1:

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

Try2:

Using for loop to get each pair, array.push and JSON.stringigy() method.

All I want to is create a stacked fusioncharts using the JSON response from database


回答1:


You could make a function that returns the array you want: You could then map through and call this on the properties in your JSON:

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

var labels = makeArray('label');

Working Example




回答2:


You can use reduce like this and return array

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)

You can also return object

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:


Why am i not using Array.prototype.map or Object.keys, because in IE8, this methods are not working. To make them work, need to add Pollyfill in the code. So here is your solution without using them

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:


You can use Array#forEach() and build new objects with the wanted properties in it.

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:


I like map() here along with getOwnPropertyNames() though the other answers are probably just as good.

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));


来源:https://stackoverflow.com/questions/37139772/want-to-split-one-single-json-objects-to-multiple-json-objects-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!