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

Filter object in array that is missing keys/properties – React

How I can filter the object in array that is missing some keys. Here is the explanation:

For example, I have a array of objects:

const array = [
  {
   a: 1,
   b: 2,
   c: 3,
   d: 4
  },
  {
   b: 6,
   c: 9,
   d: 10
  },
  {
   b: 5,
   c: 7,
   d: 10
  }
]

As we see that, there are 2 objects that missing "a" property. How I can filter and add the "a" property with value for the missing key object?

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

Thank you so much, and have a nice day!

>Solution :

You could use javascript’s filter function. Then, you could use map to iterate those objects without a and, with a spread operator, add just the a property to it, if you want a separate array with only the objects where A is missing. However, the cleanest way, if you want the same array, just adding the a property where it is missing, is to map the array and just add the property where it needs to be added.

const array = [{
    a: 1,
    b: 2,
    c: 3,
    d: 4
  },
  {
    b: 6,
    c: 9,
    d: 10
  },
  {
    b: 5,
    c: 7,
    d: 10
  }
]

//Long version, just to show you the main idea
const filteredArray = array.filter((obj) => (obj.a === undefined));
console.log(filteredArray)
const filteredArrayWithAddedValues = filteredArray.map((obj) => ({ ...obj,
  a: 100
}));
console.log(filteredArrayWithAddedValues)

//Short version, if you want the same array just adding the A property where is missing
const masterArray = array.map((obj) => {
  if (obj.a !== undefined) return obj;
  return { ...obj,
    a: 100
  }
});
console.log(masterArray)
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