1

Not sure if title is formulated correct, but I have a JS object that looks like:

parent:{
children:[
    {
        id: "1"
        user:[
            {
                id: 'aa',
                email:'aa@google.com'
            },
            {
                id: 'b',
                email:'bbb@google.com'
            },
        ]
    },
    {
        id:"2",
        user: [
            {
                id:'aa',
                email:'aa@google.com'
            },
            {
                id:'eee',
                email:'eee@google.com'
            }
        ]
    }
]

}

The object is way bigger but follows the above structure.

How would I go to get a list of topics each user is on, filtered b ID? E.g. 'aa' participates in children 1 and 2 'b' participates in child 1 etc.

I figure it out I have to map the object but not sure how to proceed after that

greatTeacherOnizuka
  • 555
  • 1
  • 6
  • 24

3 Answers3

2

Assuming, you want an object with participant as key and all topic id in an object, then you could iterate the arrays an build a property with the associated id.

var data = { project: { topics: [{ id: "1", participants: [{ id: 'aa', email: 'aa@google.com' }, { id: 'b', email: 'bbb@google.com' }, ] }, { id: "2", participants: [{ id: 'aa', email: 'aa@google.com' }, { id: 'eee', email: 'eee@google.com' }] }] } },
    result = Object.create(null);

data.project.topics.forEach(function (a) {
    a.participants.forEach(function (b) {
        result[b.id] = result[b.id] || [];
        result[b.id].push(a.id);
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can write a function like this one:

function findTopicByID(id) {
    let findedTopic = {};

    let topics = obj.project.topics;

    topics.map((topic) => {
        if(parseInt(topic.id) === id) findedTopic = topic;
    });

    return findedTopic;
}

This function return the finded topic with the corresponding id or an empty object.

Antoine Amara
  • 645
  • 7
  • 11
0

You can loop the topic array and build a new resulting array of users, if a user already exist then just update the users topic list, else create a new user with name, email, and a topic list.

let result = [];
project.topics.forEach((t) => {
  t.participants.forEach((p) => {
    let found = result.find((r) => r.name === p.id);

    if (found) {
      found.topics.push(t.id);
    } else {
      result.push({
        name: p.id,
        email: p.email,
        topics: [t.id]
      });
    }
  });
});

so now when you have the resulting array, you can just find a user and get which topics she participates in

let aa = result.find((r) => r.name === 'aa');
console.log(aa.topics);
FrankCamara
  • 348
  • 4
  • 9