Home > Back-end >  Filter object in array that is missing keys/properties - React
Filter object in array that is missing keys/properties - React

Time:08-04

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?

Thank you so much, and have a nice day!

CodePudding user response:

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)

CodePudding user response:

If you are not sure which key is missing in the options of [a,b,c,d] you can do the following:

const data = [
    {a: 1, b: 2, c: 3, d: 4},
    {a: 1, c: 3, d: 4},
    {a: 1, b: 2, c: 3},
    {b: 2, c: 3, d: 4}
]

const keys = ['a','b','c','d']

const dataWithoutMissingValues = data.map(el => {
  const diff = keys.filter(k => !Object.keys(el).includes(k))
  return diff.length > 0 ? {
    ...el, 
    ...diff.reduce((obj, key) => ({...obj, [key]: parseInt(Math.random()*10)}), {})
  } : el
})

console.log(dataWithoutMissingValues)

  • Related