如何通过JS转换数组中的json

时间:2016-09-17 08:30:22

标签: javascript json

我需要转换

中的JSON数据
  [{"Date":"2014","Amount1":90,"Amount2":800},    {"Date":"2015","Amount1":110,"Amount2":300},{"Date":"2016","Amount1":3000,"Amount2":500}]

[['Date', 'Amount1', 'Amount2'],
      ['2014',  90,      800],
      ['2015',  110,      300],
      ['2016',  3000,       500]]

我该怎么做?

3 个答案:

答案 0 :(得分:0)

使用 Array#reduce Array#map 方法。



var data = [{
  "Date": "2014",
  "Amount1": 90,
  "Amount2": 800
}, {
  "Date": "2015",
  "Amount1": 110,
  "Amount2": 300
}, {
  "Date": "2016",
  "Amount1": 3000,
  "Amount2": 500
}];

// iterate over the array value
var res = data.reduce(function(arr, o) {
  // push the new value to array
  arr.push(
    // generate object value array using the key array
    arr[0].map(function(k) {
      // return the property value
      return o[k]
    })
  );
  // return the updated array
  return arr;
  // set initial variable as array with
  // fist element as object property array
}, [Object.keys(data[0])]);

console.log(res);




答案 1 :(得分:0)

我建议为键使用辅助数组,保持属性的所需顺序,并为值保留Array#map。然后将键应用于数组的开头。



AuthenticationProperties

var data = [{ "Date": "2014", "Amount1": 90, "Amount2": 800 }, { "Date": "2015", "Amount1": 110, "Amount2": 300 }, { "Date": "2016", "Amount1": 3000, "Amount2": 500 }],
    keys = Object.keys(data[0]),
    result = data.map(function (o) {
        return keys.map(function (k) {
            return o[k];
        });
    });

result.unshift(keys);
console.log(result);




ES6



.as-console-wrapper { max-height: 100% !important; top: 0; }

var data = [{ "Date": "2014", "Amount1": 90, "Amount2": 800 }, { "Date": "2015", "Amount1": 110, "Amount2": 300 }, { "Date": "2016", "Amount1": 3000, "Amount2": 500 }],
    keys = Object.keys(data[0]),
    result = data.map(o => keys.map(k => o[k]));

result.unshift(keys);
console.log(result);




答案 2 :(得分:0)

你也可以循环2次扔你的JSON对象

var obj = [{"Date":"2014","Amount1":90,"Amount2":800},{"Date":"2015","Amount1":110,"Amount2":300},{"Date":"2016","Amount1":3000,"Amount2":500}];
var result = [];
result.push(Object.keys(obj[0]));
for (var subObj in obj){
  var arr = [];
  for (var item in obj[subObj])  arr.push(obj[subObj][item]);
  result.push(arr);
}
console.log(result); // [ [ 'Date', 'Amount1', 'Amount2' ],[ '2014', 90, 800 ],[ '2015', 110, 300 ],[ '2016', 3000, 500 ] ]