如何在 Angular 8 中重新排列对象值以成为其列表值的一部分



下面是我要重新排列的数据。

[
{ 
...,
id: 1,
value: [
{geoLat: 123123, geoLong: 123432},
{geoLat: 23240, geoLong: 234324},
{geoLat: 23240, geoLong: 234324},
]
}
{
...,
id: 2,
value: [
{geoLat: 653, geoLong: 435},
{geoLat: 12321, geoLong: 987987},
],
...
}
]

我希望寻找一个函数来分配或组合特定的 2 个值,以便当我做 _chain(( 和 group(( 时,我可以得到以下结果。

[
{ 
...,
value: [
{geoLat: 123123, geoLong: 123432, id: 1},
{geoLat: 23240, geoLong: 234324, id: 1},
{geoLat: 23240, geoLong: 234324, id: 1},
],
...
}
{
...,
value: [
{geoLat: 653, geoLong: 435, id: 2},
{geoLat: 12321, geoLong: 987987, id: 2},
],
...
}
]

您可以使用map来实现此目的。

这是一个工作示例。

const data = [{
id: 1,
value: [{
geoLat: 123123,
geoLong: 123432
},
{
geoLat: 23240,
geoLong: 234324
},
{
geoLat: 23240,
geoLong: 234324
}
]
}, {
id: 2,
value: [{
geoLat: 653,
geoLong: 435
},
{
geoLat: 12321,
geoLong: 987987
}
]
}];
const newArray = data.map(x => {
x.value.map(y => {
y['id'] = x.id;
return y
});
delete x.id;
return x;
});
console.log(newArray);

data.forEach((elem) => {
elem.value.forEach((pos) =>
pos['id'] = elem.id
);
delete elem.id;
});

最新更新