gpt4 book ai didi

javascript - 对于对象数组中每个对象中找到的值返回 true

转载 作者:行者123 更新时间:2023-11-30 23:59:03 25 4
gpt4 key购买 nike

我正在尝试在我的 React 应用程序中实现一个点赞系统,但为此我需要知道当前LoggedIn 用户之前喜欢过哪些帖子,这样我就可以显示一个不喜欢的图标,反之亦然。

我的第一个想法是创建一个接收两个参数的小函数,即登录用户和 postId。这是函数:

const clickLike = (userId, postId) => {
const match =
timeline &&
timeline.map(
post =>
post._id === postId && post.likes.filter(user => user === userId)
);
return match;
};

前面的代码应该映射所有帖子,然后如果登录用户已经在 postId 对象上,则返回 true。这是我的 JSON 的样子:

"data": [
{
"status": "published",
"_id": "5e5dcfc65104666e70558110",
"text": "Mierda!",
"user": {
"_id": "5e0925629648903308163aeb",
"username": "GodHimself",
"avatar": "//www.gravatar.com/avatar/b62ddb6758fca61fb7a56381ac7cb07d?s=200&r=pg&d=mm",
"bio": "I'm not God",
"id": "5e0925629648903308163aeb"
},
"likes": [
{
"_id": "5e76bc5fd3266e125c2dc4b9",
"user": "5e0925629648903308163aeb"
},
],
"id": "5e5dcfc65104666e70558110"
},
{
"status": "published",
"_id": "5e4a08dc4c1f0d2394f28d8e",
"text": "Initial D!",
"user": {
"_id": "5e0925629648903308163aeb",
"username": "GodHimself",
"avatar": "//www.gravatar.com/avatar/b62ddb6758fca61fb7a56381ac7cb07d?s=200&r=pg&d=mm",
"bio": "I'm not God",
"id": "5e0925629648903308163aeb"
},
"likes": [],
"id": "5e4a08dc4c1f0d2394f28d8e"
},
{
"status": "published",
"_id": "5e4a08584c1f0d2394f28d8d",
"text": "Berserk Bois!",
"user": {
"_id": "5e0925629648903308163aeb",
"username": "GodHimself",
"avatar": "//www.gravatar.com/avatar/b62ddb6758fca61fb7a56381ac7cb07d?s=200&r=pg&d=mm",
"bio": "I'm not God",
"id": "5e0925629648903308163aeb"
},
"likes": [
{
"_id": "5e4b5c889861ad1cf8b67bbb",
"user": "5e0925629648903308163aeb"
},
{
"_id": "5e4b5ca59861ad1cf8b67bbc",
"user": "5e0925629648903308163aeb"
}
],
"id": "5e4a08584c1f0d2394f28d8d"
}
]

到目前为止,代码在任何单个帖子中都会返回 true,即使是那些没有收到点赞的帖子。

如有任何帮助,我们将不胜感激。

最佳答案

使用Array.prototype.some()

const clickLike = (userId, postId) => {
return data.some(x => x._id === postId && x.likes.some(y => y._id === userId));
};

  const data = [
{
status: "published",
_id: "5e5dcfc65104666e70558110",
text: "Mierda!",
user: {
_id: "5e0925629648903308163aeb",
username: "GodHimself",
avatar:
"//www.gravatar.com/avatar/b62ddb6758fca61fb7a56381ac7cb07d?s=200&r=pg&d=mm",
bio: "I'm not God",
id: "5e0925629648903308163aeb"
},
likes: [
{
_id: "5e76bc5fd3266e125c2dc4b9",
user: "5e0925629648903308163aeb"
}
],
id: "5e5dcfc65104666e70558110"
}
];
const clickLike = (userId, postId) => {
return data.some(x => x._id === postId && x.likes.some(y => y._id === userId));
};
console.log(
clickLike("5e76bc5fd3266e125c2dc4b9", "5e5dcfc65104666e70558110"),
clickLike("xxx", "5e5dcfc65104666e70558110"),
clickLike("5e76bc5fd3266e125c2dc4b9", "xxx"),
clickLike("xxx", "xxx")
);

关于javascript - 对于对象数组中每个对象中找到的值返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60862213/

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