Reputation: 1020
I am trying to format my object array into an array to be used by a component. I need to map the exact values of the object to the correct positions.
e.g.
My Raw Data:
var rawData = [
{ name: 'john',
age: 23,
style : 'expert',
max : 'none'
},
{ name: 'mick',
age: 36,
style : 'inter',
max : 'none'
},
{ name: 'pete',
age: 44,
style : 'med',
max : 'none'
}
]
i would like to use underscore.js to convert this object to the following array format so I can use in my component which requires this format.
Please note only name
age
and style
are required not max
. I have more undesired properties but for example above I did not want to write all.
var result = [
[ "john", "23", "expoert"],
[ "mick", "36", "inter"],
[ "pete", "44", "med"]
]
I have tried pluck
and map
combinations, but can't seem to get the order correct in the outputted array. Any help appreciated.
Upvotes: 2
Views: 276
Reputation: 138257
const rawData = [
{ name: 'john', age: 23, style : 'expert' },
{ name: 'mick', age: 36, style : 'inter' }
];
const result = rawData.map(Object.values);
console.log(result);
Theres no need to use a library at all. Or more explicitly:
const rawData = [
{ name: 'john', age: 23, style : 'expert' },
{ name: 'mick', age: 36, style : 'inter' }
];
const result = rawData.map(({name, age, style}) => [name, age, style]);
console.log(result);
I would prefer this as object key/value order is not guaranteed.
Upvotes: 6
Reputation: 171679
This is trivial without any library using Array#map()
and Object.values()
var rawData = [{
name: 'john',
age: 23,
style: 'expert'
}, {
name: 'mick',
age: 36,
style: 'inter'
}, {
name: 'pete',
age: 44,
style: 'med'
}]
var res = rawData.map(o=>Object.values(o))
console.log(res)
Upvotes: 1