我有两个数据数组。一个数组(allGroups)包含用户关注和未关注的所有组的数据,另一个数组(followingGroups)仅包含用户关注的组的列表。现在,我想将 allGroups 数组数据 id 与 followGroups 数组数据 id 进行比较,我需要找到它们,它们都具有相同的 id。我需要列出所有组,如果一个组具有相同的 id,我需要显示,用户正在 View 中关注该组,否则请关注。请让我知道,我怎样才能实现这一目标。请检查我下面的数组数据。
//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"}}
]
最佳答案
很简单,只需选择您要比较的字段即可,您还应该阅读此文档 array loop
const allGroups = [
{"id": 0, "name": "books", "purpose": "to read"},
{"id": 1, "name": "dress", "purpose": "to wear"},
];
const userGroups = [
{"following":{"id": 0, "name": "shoe", "purpose": "to walk"}},
{"following":{"id": 3, "name": "food", "purpose": "to eat"}},
{"following":{"id": 4, "name": "nature", "purpose": "to view"}}
];
// Collect ids of allGroups
const ids = allGroups.map(group => group.id);
const sameGroup = userGroups.map(group => {
const { following } = group;
if (ids.includes(following.id)) {
console.log(JSON.stringify(group))
return group; // return group with id: 0
}
});
关于javascript - 比较两个数组的 id | Reactjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397108/