简体   繁体   中英

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) { ... }

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM