Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS intersection of array and object of arrays

I want to delete some item from my object :

clientData : {
1111 : [
  {ID : 112, name : 'John',age : 23},
  {ID : 113, name : 'Doe',age : 21},
  {ID : 114, name : 'Stan',age : 24},
],

2222 : [
  {ID : 222, name : 'Sara',age : 15},
  {ID : 223, name : 'Wiliams',age : 61},
  {ID : 224, name : 'Alan',age : 45},
],

}

The data that I want to delete is stored in an array of Id’s like this :

[112,223,114]

So the output should look like this :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

clientData : {
1111 : [
  {ID : 113, name : 'Doe',age : 21},
],
2222 : [
  {ID : 222, name : 'Sara',age : 15},
  {ID : 224, name : 'Alan',age : 45},
],
}

Any help please how to achieve this ? I really have no idea how to do it, and don’t found any solutions in internet.

>Solution :

I am assuming you are tying to filter out the original object. Hence, You can simply achieve it by using Array.forEach() method along with the Array.splice().

Live Demo :

const clientData = {
  1111 : [
    {ID : 112, name : 'John',age : 23},
    {ID : 113, name : 'Doe',age : 21},
    {ID : 114, name : 'Stan',age : 24},
  ],
  2222 : [
    {ID : 222, name : 'Sara',age : 15},
    {ID : 223, name : 'Wiliams',age : 61},
    {ID : 224, name : 'Alan',age : 45},
  ]
};

const invalidValues = [112, 223, 114];

Object.keys(clientData).forEach(key => {
    clientData[key].forEach((obj, index) => {
    if (invalidValues.includes(obj.ID)) {
        clientData[key].splice(index, 1);
    }
  })
});

console.log(clientData);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading