我需要一种适当的方法来拆分此对象并将其分组。 预先谢谢你
let data = [{
name: 'DAVID/JOHN',
amount: '1231.21/131.93',
identity: '1880/1332',
address: 'first/second'
}]
预期结果
let result = [
{
name: 'DAVID',
amount: '1231.21',
identity: '1880',
address: 'first'
},
{
name: 'JOHN',
amount: '131.93',
identity: '1332',
address: 'second'
}
]
答案 0 :(得分:3)
您可以使用[Array.flatMap()][1]
或lodash的_.flatMap()
来迭代数组,取每个对象的entries,然后用Array.reduce()
和{{ 3}}:
let data = [{
name: 'DAVID/JOHN',
amount: '1231.21/131.93',
identity: '1880/1332',
address: 'first/second'
}]
const result = data.flatMap(o =>
Object.entries(o)
.reduce((r, [k, v]) => {
v.split('/').forEach((p, i) => {
if (!r[i]) r[i] = {}
r[i][k] = p;
})
return r
}, [])
)
console.log(result)
答案 1 :(得分:3)
这里使用地图方法。
let data = [{
name: 'DAVID/JOHN',
amount: '1231.21/131.93',
identity: '1880/1332',
address: 'first/second'
}]
let result = data.flatMap(e => {
return e.name.split('/').map((v,i) => {
return {
name: v,
amount: e.amount.split('/')[i],
identity: e.identity.split('/')[i],
address: e.address.split('/')[i]
}
});
});
console.log(result);