I'm wondering what the best way would be to transform my javascript array with objects. I have tried making a fancy chain with lodash but I can't figure it out.
I need to format the data this way because of the way the backend works.
// from:
var something = [
{
name: 'foo',
stuff: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
},
{
name: 'bar',
stuff: []
},
{
name: 'baz',
stuff: [
{
id: 7
},
{
id: 8
}
]
}
];
// to:
var transformed = [
{
name: 'foo',
included: {
included: [1, 2, 3]
}
},
{
name: 'bar',
included: {
included: []
}
},
{
name: 'baz',
included: {
included: [7, 8]
}
}
];
You can do this quite concisely with two map
calls (the array built in or lodash's map), one nested to handle the "included"
array within each object:
const transformed = something.map(it => {
return {
name: it.name,
included: {
included: it.stuff.map(thing => thing.id)
}
};
});
No need for lodash
, just use the Array.prototype.map
function :
// Sorry no fancy ES6 => here :S
var res = something.map(function(item) {
item.included = {included : item.stuff.map(function(i) {return i.id})}
delete(item.stuff)
return item
})
Per @ssube 's comment:
var res = something.map(function(item) {
return {
included : {included : item.stuff.map(function(i) {return i.id})},
name: item.name
}
})
See this fiddle
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.