将对象数组转换为Array Angularjs

时间:2017-04-25 14:43:19

标签: angularjs arrays

angularJs中是否有任何可能的方法来转换此对象数组:

[{"tickets":1,"month":"june","year":2016},{"tickets":2,"month":"june","year":2015},{"tickets":3,"month":"december","year":2015}]

到这样的数组:

[['tickets', 'month','year'], [1, "june",2016],[3, "june",2015],[1, "december",2015]]

2 个答案:

答案 0 :(得分:1)

使用Array#reduce()Array#concat()的方法不依赖于知道任何属性名称或硬编码结果数组结构



let data = [{"tickets":1,"month":"june","year":2016},{"tickets":2,"month":"june","year":2015},{"tickets":3,"month":"december","year":2015}];

let res = data.reduce((acc, curr) => {
  return acc.concat([acc[0].map((key) => curr[key])]);
}, [Object.keys(data[0])]);

console.log(res)




答案 1 :(得分:-1)

当然,它的纯JavaScript可以处理

var array1 = [{"tickets":1,"month":"june","year":2016},
     {"tickets":2,"month":"june","year":2015},
     {"tickets":3,"month":"december","year":2015}];

  var array2 = [['tickets', 'month','year']];

 array1.forEach(function(item){
   array2.push([item.tickets, item.month, item.year]);
 })
 
 console.log(array2);

<强>更新

更灵活的方式,JK_Jha

提供建议

var array1 = [{"tickets":1,"month":"june","year":2016},
         {"tickets":2,"month":"june","year":2015},
         {"tickets":3,"month":"december","year":2015}];

var array2 = [Object.keys(array1[0])];

array1.forEach(function(item){
     array2.push([item.tickets, item.month, item.year]);
 })

console.log(array2);