我有两个数据数组。一个数组(allGroups)包含用户所有关注和不关注组的数据,另一个数组(followingGroups)只包含用户关注的组列表。现在,我想将 allGroups 数组数据 id 与 followingGroups 数组数据 id 进行比较,我需要找到它们都具有相同的 id。我需要列出所有组,如果一个组具有相同的 id,我需要显示,用户在视图中关注该组,否则请关注。请让我知道,我怎样才能做到这一点。请检查我下面的数组数据。
//allGroups array
allGroups = [
{"id": 0, "name": "books", "purpose": "to read"},
{"id": 1, "name": "dress", "purpose": "to wear"},
{"id": 2, "name": "shoe", "purpose": "to walk"},
{"id": 3, "name": "food", "purpose": "to eat"},
{"id": 4, "name": "nature", "purpose": "to view"}
]
//followingGroups array
followingGroups = [
{"following":{"id": 2, "name": "shoe", "purpose": "to walk"}},
{"following":{"id": 3, "name": "food", "purpose": "to eat"}},
{"following":{"id": 4, "name": "nature", "purpose": "to view"}}
]
let allGroups = [
{"id": 0, "name": "books", "purpose": "to read"},
{"id": 1, "name": "dress", "purpose": "to wear"},
{"id": 2, "name": "shoe", "purpose": "to walk"},
{"id": 3, "name": "food", "purpose": "to eat"},
{"id": 4, "name": "nature", "purpose": "to view"}
];
let followingGroups = [
{"following":{"id": 2, "name": "shoe", "purpose": "to walk"}},
{"following":{"id": 3, "name": "food", "purpose": "to eat"}},
{"following":{"id": 4, "name": "nature", "purpose": "to view"}}
];
let followingIds = followingGroups.map(group => group.following.id);
let allGroupsUserSpecific = allGroups.map(group => (
{...group, following: followingIds.includes(group.id)})
);
这段代码创建了一个新的allGroups
被调用数组,allGroupsUserSpecific
其中包含一个标志来告诉前端用户是否已经在关注该组。如果您记录allGroupsUserSpecific
var,这是输出...
{id: 0, name: "books", purpose: "to read", following: false}
{id: 1, name: "dress", purpose: "to wear", following: false}
{id: 2, name: "shoe", purpose: "to walk", following: true}
{id: 3, name: "food", purpose: "to eat", following: true}
{id: 4, name: "nature", purpose: "to view", following: true}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句