Search code examples
javascriptarraysmergelodashjavascript-objects

How do I exclude null values when merging objects by key?


Lets say I have an array of objects in Javascript:

  id: 1,
  name: 'Snowy',
  },
  {
  id: 2,
  name: 'Quacky',
  age: 13
  },
  {
  id: 3,
  name: 'Snowy',
  age: 1,
  },
  {
    name: null
  }
]

I have created a function to arrange them by a key:

const filter = 
        (pets, key) =>
                _(pets)
                .filter(pets => _.has(pets, key))
                .groupBy(key)
                .value()

Although, the output of this function when called persists the null entry:

{
  Snowy: [ { id: 1, name: 'Snowy' }, { id: 3, name: 'Snowy', age: 1 } ],
  Quacky: [ { id: 2, name: 'Quacky', age: 13 } ],
  null: [ { name: null } ]
}

Is there I way I can filter out any of the null values here?


Solution

  • You could try by changing the method you use in in your predicate function from _.has to _.get.

    So, instead of checking if a path/ key exist in an object, you instead check the value of a path/ key within an object it its null or not.

    note: you might also want to check for falsy values here (such as undefined) instead of just null, since _.get returns undefined if the path/ key does not exist

    const pets = [{
        id: 1,
        name: 'Snowy',
      },
      {
        id: 2,
        name: 'Quacky',
        age: 13
      },
      {
        id: 3,
        name: 'Snowy',
        age: 1,
      },
      {
        name: null
      }
    ];
    
    const filter = 
            (pets, key) =>
                    _(pets)
                    .filter(pets => _.get(pets, key) !== null)
                    .groupBy(key)
                    .value();
                    
    console.log(filter(pets, 'name'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>