gpt4 book ai didi

JavaScript 将对象数组映射到新对象数组的最短方法?

转载 作者:行者123 更新时间:2023-12-03 16:29:04 24 4
gpt4 key购买 nike

我有一组 person 对象,其中每个 person 都有一组 profiles 对象,其中包含名称和图像 url,以及由 latlong 属性组成的地址对象列表,如下所示:

var listOfPersons = [{
addresses : [{lat:11, long:11}, {lat:22, long:22}],
profile: [{image:"some_url1", name: "peter parker"}]
},
{
addresses : [{lat:33, long:33}, {lat:44, long:44}],
profile: [{image:"some_url2", name: "bruce wayne"}]
}];

我需要创建一个新的对象数组,其中每个新对象都有一个 imagelonglat 属性,用于 每组 lat long,如下:

var expectedResult = [
{
image:"some_url1",
lat:11,
long:11
},
{
image:"some_url1",
lat:22,
long:22
},
{
image:"some_url1",
lat:33,
long:33
},
{
image:"some_url1",
lat:44,
long:44
}
];

map\reduce 第一个数组到第二个数组的最短方法(就编写代码而言)是什么?

最佳答案

您可以使用嵌套的 Array.flatMap()Array.map() 来迭代数组/地址/配置文件,并组合 imagelatlong 属性合并到一个对象中:

const listOfPersons = [{"addresses":[{"lat":11,"long":11},{"lat":22,"long":22}],"profile":[{"image":"some_url1","name":"peter parker"}]},{"addresses":[{"lat":33,"long":33},{"lat":44,"long":44}],"profile":[{"image":"some_url2","name":"bruce wayne"}]}];

const result = listOfPersons.flatMap(o =>
o.addresses.flatMap(({ lat, long }) =>
o.profile.map(({ image }) => ({
image,
lat,
long
}))
)
);

console.log(result);

如果您始终只使用第一个配置文件,则可以删除一层 Array.flatMap():

const listOfPersons = [{"addresses":[{"lat":11,"long":11},{"lat":22,"long":22}],"profile":[{"image":"some_url1","name":"peter parker"}]},{"addresses":[{"lat":33,"long":33},{"lat":44,"long":44}],"profile":[{"image":"some_url2","name":"bruce wayne"}]}];

const result = listOfPersons.flatMap(o =>
o.addresses.map(({ lat, long }) => ({
image: o.profile[0].image,
lat,
long
}))
);

console.log(result);

关于JavaScript 将对象数组映射到新对象数组的最短方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59631246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com