Arrays in JSON filtering same name with different ID and value

Viewed 32

everyone. I have got 3 JSON objects of arrays. One got informations about users second about devices and thirth one about devices connected to the device from obj number two.


    Object 1 : {
        "id": "b3836a54-31f7-427b-a2d2-2d09323c7ab5",
        "name": "Alice - 1"
    }
    
    Object 2 : {
       "id": "1067daa9-7b59-456f-8cd1-79f38c2b0c10",
        "name": "Device - 2",
        "user": "b3836a54-31f7-427b-a2d2-2d09323c7ab5"// == id from object number 1
    }
    
      Object 3: {
      "id": "274ffcd5-d86b-4b8a-bb8e-4b4f90095ca4",
      "name": "IOT - 3",
      "mobile": "d8a18ca2-e398-4863-84c5-8cc009f4d241"== id from object 2
}

example data from object they contain multiple records like that

My code

    mobileDevices.forEach(item => {
        let sum = 0;
        for (let i = 0; i < iotDevices.length; i++) {
    
          if (item.id === iotDevices[i].mobile) {
            iotDevices[i].mobile = 1;
            sum += iotDevices[i].mobile;
          }
    
          for (let j = 0; j < users.length; j++) {
    
            if (item.user === users[j].id) {
              var usersNames = JSON.stringify(users[j].name).replace(/[0-9/-/" "/-]/g, '');
            } 
          }
        }
        console.log(`${usersNames} amount ${sum} `)
    })

result

    Alice amount 2 
    Alice amount 4
    Bob amount 3
    Bob amount 2
    Martin amount 4
    Henry amount 3
    Olaf amount 3
    Olaf amount 4
    Alice amount 4
    Alice amount 4
    Bob amount 3
    Bob amount 3
    Martin amount 2
    Martin amount 2
    Olaf amount 3

But what am I looking for is result like that

   example
   Alice amount 6
   Bob amount 5
   Olaf amount 10

and goes on.

What is the best way to filter those informations like that? they have got same names but different id's and also different amount of devices

1 Answers

you need to first get all unique names and only then do what you need to do. Little example on how to get unique primitive values:

const namesUnfiltered = ["Alice", "Bob", "Alice"];
const uniqueNames = [...new Set(namesUnfiltered)];
console.log(uniqueNames); // ["Alice", "Bob"]
Related