我想知道用对象转换javascript数组的最佳方法是什么。我试过用lodash制作一个花哨的链条,但我无法弄明白。
由于后端的工作方式,我需要以这种方式格式化数据。
// 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]
}
}
];
答案 0 :(得分:2)
您可以通过两个map
调用(内置数组或lodash的映射)非常简洁地完成此操作,一个嵌套用于处理每个对象中的"included"
数组:
const transformed = something.map(it => {
return {
name: it.name,
included: {
included: it.stuff.map(thing => thing.id)
}
};
});
答案 1 :(得分:1)
不需要lodash
,只需使用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 的评论:
var res = something.map(function(item) {
return {
included : {included : item.stuff.map(function(i) {return i.id})},
name: item.name
}
})
请参阅this fiddle