将一个数组的项属性合并到另一数组的项中



我有几个问题,关于做以下事情的最佳方法是什么:

  1. 调用两个不同的API:

    axios.get(contents);
    axios.get(favorites);
    
  2. 回复如下:

    contents: [
    {
    id: 1,
    value: someValue
    },
    {
    id: 2,
    value: someValue
    }
    ];
    favorites: [
    {
    id: 1,
    contentId: 2    
    }
    ];
    

contentIdid匹配时,循环浏览每个收藏夹并向内容数组添加元素(如isFavorite: true(的最佳方法是什么。它应该如下所示:

contents: [
{
id: 1,
value: someValue
{,
{
id: 2,
value: someValue
isFavorite: true
{
];

做这件事的最佳地点是什么?有没有ES6语法可以轻松做到这一点?我目前有两个单独的操作,一个获取内容,另一个获取收藏夹,我可以在reducer中合并或组合它们。

有什么建议吗?

您可以使用Setfavorites收集所有contentId值,然后在contents数组中迭代。这比在阵列上使用some具有更好的时间复杂性,因为在Set上调用.has()O(1(:

let contents = [{
id: 1,
value: 'someValue1'
},
{
id: 2,
value: 'someValue2'
},
{
id: 3,
value: 'someValue'
}
];
let favorites = [{
id: 1,
contentId: 2
},
{
id: 2,
contentId: 3
}
];
let favoriteContents = new Set(favorites.map(f => f.contentId));
contents.forEach(c => {
if (favoriteContents.has(c.id)) c.isFavorite = true;
});
console.log(contents);

const newContents = contents.map((content) => {
const foundFavorite = favorites.find((favorite) => favorite.contentId === content.id)
if (foundFavorite) {
return {
...content,
isFavorite: true,
}
}
return content
});

首先需要获得API调用的promise,当这两个调用都完成后,您可以对结果进行合并。

const contentsApi = () => Promise.resolve([
{
id: 1,
value: 'foo'
},
{
id: 2,
value: 'bar'
}
])
const favouritesApi = () => Promise.resolve([
{
id: 1,
contentId: 2    
}
])
let contents;
let favourites;
const contentsApiCall = contentsApi().then(res => {
contents = res;
})
const favouritesApiCall = favouritesApi().then(res => {
favourites = res;
})

Promise.all([contentsApiCall, favouritesApiCall]).then(() => {
const merged = contents.map(content => {
if(favourites.some(favourite => favourite.contentId === content.id)){
return {
...content,
isFavourite: true
}
} else {
return content;
}
})
console.log(merged)
// do whatever you need to do with your result, either return it if you want to chain promises, or set it in a variable, etc.
})

最新更新