0

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
Cerr
  • 9
  • 1
  • You haven't posted any sample input data, and the output format you want isn't obviously related to the output you're getting. Please edit the question to provide actual input data and the result it provides and the result you want. – Tangentially Perpendicular Sep 10 '22 at 23:12
  • Please post the valid `JSON` data that you're working with. – ThS Sep 10 '22 at 23:13
  • Typo. You have `if (item.id === iotDevices[i].mobile)` where you meant to write `if (item.id === iotDevices[i].id)`. That's still going to print each name multiple times, but each line will have the proper sum. – Tim Roberts Sep 10 '22 at 23:17

1 Answers1

0

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"]
rickshinova
  • 109
  • 6