Search code examples
javascriptarraysobjectkey

JavaScript return array of keys that are all empty in array of objects


I have an array of objects

const arrayOfObjects = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}];

I need to return an array of keys that are empty in all of the objects in the array. So for the above example, it would return ['firstKey', 'fourthKey'] but not 'secondKey', because it is only empty in one of the objects.

I have found a lot of examples (like one below) that return boolean but having trouble finding a way to return the actual empty keys. Thanks

const isEmpty = Object.values(object).every(x => (x === ''));

Solution

  • Get the keys from the 1st object in the array, and then filter them by checking for each key that it's empty in all objects with Array.every():

    const checkAllEmpty = arr =>
      Object.keys(arr[0] ?? {}) // get the keys from the 1st object or use an empty object as fallback
        .filter(key => arr.every(o => o[key] === '')) // filter the keys by checking each object in the array
    
    const arr = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}]
    
    const result = checkAllEmpty(arr)
    
    console.log(result)

    Old answer:

    Reduce the array to a Map, and count how many times a key is empty. Convert the Map to an an array of [key, value] using Array.from(), filter all the entries that have a value that is less then the array's length, and map to an array of keys:

    const arr = [{firstKey: '', secondKey: 'someValue', thirdkey: 'someValue', fourthKey: ''},{firstKey: '', secondKey: '', thirdkey: 'someValue', fourthKey: ''}]
    
    const result = Array.from(arr.reduce((acc, obj) => {
        Object.entries(obj)
          .forEach(([k, v]) => {
            if (v === '') acc.set(k, (acc.get(k) ?? 0) + 1)
          })
    
        return acc
      }, new Map))
      .filter(([, v]) => v === arr.length)
      .map(([k]) => k)
    
    console.log(result)