Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash. How to groupBy except undefined

Trying to group up array of object to get unique properties with Lodash

But it takes undefined like unique property if property does not exists

Is there way how to avoid it? and left only existing properties ?

So i'm going to achieve only My Office 1 but with my solution getting undefined and My Office 1 Example array

[
        {office: null},
        {office: 
            {
                name: 'My Office 1'
            }
        }
]

code

Object.keys(_.groupBy(arr, 'office.name')).map((office, index) { ... }
like image 497
Андрей Гузюк Avatar asked May 24 '17 09:05

Андрей Гузюк


1 Answers

You can just filter out the objects, which do not have the path.

let objects = [
  {office: null},
  {office: {name: 'My Office 1'}},
  {office: {name: 'My Office 2'}},
  {office: {name: 'My Office 1'}},
];

let path = 'office.name';
let grouped = _(objects)
  .filter(object => _.has(object, path))
  .groupBy(path)
  .value();

console.log(grouped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 105
SeregPie Avatar answered Oct 20 '22 08:10

SeregPie