gpt4 book ai didi

javascript - javascript中两个对象数组的算法混合信息?

转载 作者:行者123 更新时间:2023-12-04 09:02:17 26 4
gpt4 key购买 nike

问题
我有这个数组

const cards = [
{id: "29210z-192011-222", power: 0.9}, // Card A
{id: "39222x-232189-12a", power: 0.2} // Card B
...
]
我的 Firestore 数据库如下所示:

cards (collection) -> cardId (document) -> userId (a "Foreign Key" to the card's owner, in the document data)


因此,我为阵列中的每张卡获取了相应的所有者:
const documentRefs = cards.map((card) =>
firestore.collection("cards").doc(card.id)
);

const rivalPlayers = db.collection("cards")
.getAll(...documentRefs)
.then((docs) => {
return docs.map(doc => {
console.log(doc.data); // { userId: "219038210890-234-22-a" }
/*
TODO - Here I need to return an object containing the userId (from doc.data)
and the power of the card which referenced him
*/
})
})
.catch(err => throw err);
正如您在代码中看到的那样,我需要一个如下所示的数组“rivalPlayers”:
[{userId: "219038210890-234-22-a", power: 0.9}, {userId: "519aa821Z890-219-21-e", power: 0.2}]
钯: 这个数组不能包含当前用户,所以我过滤它

有人知道在这种情况下如何混合数组信息吗?我的意思是,在我从 firebase 映射文档的那一刻,我有 userId(对应于 card 数组中的一张卡片)和 cardId(doc.id,因为我的数据库中的每个文档 ID 都是一个卡片 ID),但是我不知道如何让每个电源都具有良好的性能。
我很感激该解决方案是用现代 javascript 编写的。谢谢。
我最好的方法
const rivalPlayers = db.collection("cards")
.getAll(...documentRefs)
.then((docs) => {
return docs.map(doc => ({
userId: doc.data.userId,
power: cards.filter(card => card.id === doc.id)[0].power // <----------- That is the main point of the question
})).filter(player => player.userId !== currentUser.userId) // This part is irrelevant to my question
})
.catch(err => throw err);
快试试这个代码
我知道这个场景的构建时间有点长,因为你必须重新创建 firebase 数据库等......
这是没有从 firebase 获取数据的相同代码:
const cards = [
{id: "29210z-192011-222", power: 0.9}, // Card A
{id: "39222x-232189-12a", power: 0.2} // Card B
]

const usersIds = [
{
id: "39222x-232189-12a", // Firebase doc.id === card id
data: {
userId: "329u4932840" // Id of the owner of the card
}
},
{
id: "29210z-192011-222", // Firebase doc.id === card.id
data: {
userId: "8u4394343" // Id of the owner of the card
}
}
]

const rivalPlayers = usersIds.map(doc => ({
userId: doc.data.userId,
power: cards.filter(card => card.id === doc.id)[0].power
}));

console.log(rivalPlayers)
试试看 https://playcode.io/例如。

最佳答案

将所有功率值放在一个 Map 中,这样您只需遍历卡片一次,而不是运行 filter()多次

const cards = [{id: "29210z-192011-222", power: 0.9}, {id: "39222x-232189-12a", power: 0.2}];

const powerMap = new Map(cards.map(({id, power}) => [id, power]));
const wantedId = "39222x-232189-12a"

console.log('Power for id:', wantedId , 'is:', powerMap.get(wantedId))

关于javascript - javascript中两个对象数组的算法混合信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63538940/

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