-2

I have an array of objects,

[
 {trial1: 'a1', trial2: 'a2', trial3: 'a3'},
 {trial1: 'b1', trial2: 'b2', trial3: 'b3'},
 {trial1: 'c1', trial2: 'c2', trial3: 'c3'},
 ]

How do I get an array of arrays like this

[
 ['a1','a2','a3'],
 ['b1','b2','b3'],
 ['c1','c2','c3']
]

And also an array like this

[
 ['a1','b1','c1'],
 ['a2','b2','c2'],
 ['a3','b3','c3']
]
Neha
  • 49
  • 6

2 Answers2

2

Use .map(Object.values):

let data = [
 {trial1: 'a1', trial2: 'a2', trial3: 'a3'},
 {trial1: 'b1', trial2: 'b2', trial3: 'b3'},
 {trial1: 'c1', trial2: 'c2', trial3: 'c3'},
];

let result = data.map(Object.values);

console.log(result);

When you need to transpose:

let data = [
 {trial1: 'a1', trial2: 'a2', trial3: 'a3'},
 {trial1: 'b1', trial2: 'b2', trial3: 'b3'},
 {trial1: 'c1', trial2: 'c2', trial3: 'c3'},
];

let result = data.map(Object.values);
result = result[0].map((_, i) => result.map(row => row[i]));

console.log(result);
trincot
  • 263,463
  • 30
  • 215
  • 251
1

You can do it by using map and Object.values like this:

const data = [
 {trial1: 'a1', trial2: 'a2', trial3: 'a3'},
 {trial1: 'b1', trial2: 'b2', trial3: 'b3'},
 {trial1: 'c1', trial2: 'c2', trial3: 'c3'},
 ];
const values = data.map(Object.values).map((item,i,self) => self.map(o => o[i]) );
console.log(values)
Saeed Shamloo
  • 5,368
  • 1
  • 4
  • 17