我有一组对象数据,如下面的结构:
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"]
]
答案 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
从对象获取所有唯一键的第一个元素,然后使用map
和Object.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)