-1

I have an array of object data like the following structure:

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

I want to convert this into an array of arrays like this structure:

var expextedData=[
    ["category","name","model"],
    ["phone","Apple","5s"],
    ["phone","Moto","g4"]
]
jmcampbell
  • 378
  • 4
  • 17

3 Answers3

1

Use Array#map to iterate the array, and with Array#reduce to convert each object to it's values.

I'm using a hard coded array of keys instead of using Object#keys to extract them because 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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

you can get values in each object and add that to an array and keys from any one object also can be pushed. something like this:

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);
Dij
  • 9,761
  • 4
  • 18
  • 35
0

You can use Set to get first element of all unique keys from object and then map and Object.values to get 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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176