I have a list of project data as below, the data in the object is based on the projectId. I am now trying to make a new data object that will be formatted based on userId to see which user has which projectId.
const projects = [
{
projectId: "abc123",
name: "Project 1",
userProjects: [
{
userId: "xyz789",
projectId: "abc123",
user: {
userId: "xyz789",
email: "[email protected]"
},
},
{
userId: "sdf012",
projectId: "abc123",
user: {
userId: "sdf012",
email: "[email protected]"
},
},
],
},
{
projectId: "def456",
name: "Project 2",
userProjects: [
{
userId: "xyz789",
projectId: "def456",
user: {
userId: "xyz789",
email: "[email protected]"
},
},
],
},
]
Below is my code that I am able to get all the existing users and all the existing projects.
const userInfo = [];
const projectInfo = [];
for (let i = 0; i < projects.length; i++) {
const userProject = projects[i].userProjects;
for (let j = 0; j < userProject.length; j++) {
const projectExist = projectInfo.some((project) =>
project.projectId.includes(userProject[j].projectId)
);
if (!projectExist)
projectInfo.push({
projectId: projects[i].projectId,
name: projects[i].name,
});
const userExist = userInfo.some((item) =>
item.userId.includes(userProject[j].user.userId)
);
if (!userExist)
userInfo.push({
userId: userProject[j].user.userId,
email: userProject[j].user.email,
project: projectInfo,
});
}
}
However, I am having to implement that which user owns which project. If now I print out the userInfo, it will show up both users has both projects in the array, which is not correct (user sdf012 only has the abc123).
Also, I am bad at data formatting like this task. Are there any resources you would recommend to learn? It is so important as I work with MongoDB and sometimes need to retrieve data and modify data to different specific formatting.
Thank you for the help!!!