将对象数组转换为数组数组

时间:2017-07-18 17:28:31

标签: javascript arrays object arraylist type-conversion

我有一组对象数据,如下面的结构:

var mydata=[
          {"category" :"phone","name":"Apple","model":"5s"},
          {"category" :"phone","name":"Moto","model":"g4"}
         ]

我想将其转换为像这样结构的数组数组:

var expextedData=[
    ["category","name","model"],
    ["phone","Apple","5s"],
    ["phone","Moto","g4"]
]

3 个答案:

答案 0 :(得分:1)

使用Array#map迭代数组,并使用Array#reduce将每个对象转换为其值。

我使用硬编码键组而不是使用Object#键来提取它们,因为the order of an object properties is not guaranteed



var mydata=[
  {"category" :"phone","name":"Apple","model":"5s"},
  {"category" :"phone","name":"Moto","model":"g4"}
];
 
var keys = ["category","name","model"];

var result = [keys].concat(mydata.map(function(obj) {
  return keys.reduce((arr, key) => {
    arr.push(obj[key]);

    return arr;
  }, [])
}));

console.log(result);




答案 1 :(得分:0)

您可以在每个对象中获取值并将其添加到数组中,也可以推送来自任何一个对象的键。像这样的东西:

var mydata=[
      {"category" :"phone","name":"Apple","model":"5s"},
      {"category" :"phone","name":"Moto","model":"g4"}
     ]
var arr = [];

arr.push(Object.keys(mydata[0]));

mydata.forEach(function(ob){
arr.push(Object.values(ob));
})

console.log(arr);

答案 2 :(得分:0)

您可以使用Set从对象获取所有唯一键的第一个元素,然后使用mapObject.values来获取值。



var mydata=[{"category" :"phone","name":"Apple","model":"5s"},{"category" :"phone","name":"Moto","model":"g4"}]

var result = [[...new Set([].concat(...mydata.map(Object.keys)))], ...mydata.map(Object.values)]
console.log(result)