[英]Transform javascript array with objects with lodash
我想知道最好的方法是用對象轉換我的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]
}
}
];
您可以使用兩個map
調用(內置數組或lodash的映射)非常簡潔地完成此操作,一個嵌套以處理每個對象中的"included"
數組:
const transformed = something.map(it => {
return {
name: it.name,
included: {
included: it.stuff.map(thing => thing.id)
}
};
});
不需要lodash
,只需使用Array.prototype.map
函數 :
// 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
}
})
看到這個小提琴
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.