如何将API返回的嵌套对象数组转换为指定结构的单一对象数组?
如何合并Profile与Photos数组得到目标结构?
你之前拆分小函数的思路没问题,但最后合并的方式踩坑啦——[...profiles, { photos: photos }]是把整个photos数组当成一个新元素塞进了profiles数组末尾,这就导致结果里多了个单独的photos对象,而不是给每个profile都配上对应的photos。
这里给你两种靠谱的解决办法:
方法一:一次遍历直接转换(最简洁高效)
直接在遍历原数组时,把每个元素的profile属性展开,同时补上对应的photos属性,一步到位完成转换:
const profilesData = [ { profile: { id: "26144385", some: "more", other: "misc" }, photo_details: { photos: [{ small: "bar-1", medium: "baz-1" }] } }, { profile: { id: "26144334", some: "even", other: "some more" }, photo_details: { photos: [ { small: "bar-2", medium: "baz-2" }, { small: "fizz-2", medium: "buzz-2" } ] } } ]; const profileWithPhotos = profilesData.map(item => { return { ...item.profile, // 展开profile里的所有属性 photos: item.photo_details.photos // 添加对应的photos属性 }; }); console.log(profileWithPhotos);
方法二:基于你拆分的小函数来合并
如果想保留你之前拆分小函数的逻辑,那可以利用数组索引,把profiles和photos数组里对应位置的元素逐一合并:
const profilesData = [ { profile: { id: "26144385", some: "more", other: "misc" }, photo_details: { photos: [{ small: "bar-1", medium: "baz-1" }] } }, { profile: { id: "26144334", some: "even", other: "some more" }, photo_details: { photos: [ { small: "bar-2", medium: "baz-2" }, { small: "fizz-2", medium: "buzz-2" } ] } } ]; const getProfiles = profilesData => profilesData.map(profileData => profileData.profile); const getPhotos = profilesData => profilesData.map(profileData => profileData.photo_details.photos); const profiles = getProfiles(profilesData); const photos = getPhotos(profilesData); // 遍历profiles,用索引取对应位置的photos合并 const profileWithPhotos = profiles.map((profile, index) => ({ ...profile, photos: photos[index] })); console.log(profileWithPhotos);
两种方法都能得到你想要的profileWithPhotos结构,第一种更高效,不需要额外存储profiles和photos两个中间数组~
内容的提问来源于stack exchange,提问作者Amit Erandole
相关产品推荐
相关产品推荐

