admin管理员组

文章数量:1287879

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

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) { ... }
Share Improve this question asked May 24, 2017 at 9:17 Андрей ГузюкАндрей Гузюк 2,1646 gold badges31 silver badges56 bronze badges 1
  • 1 I don't think that's possible. undefined is a valid grouping in this case. You'll have to do a filter before or after your groupBy. – shotor Commented May 24, 2017 at 9:41
Add a ment  | 

1 Answer 1

Reset to default 12

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./ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

本文标签: javascriptLodash How to groupBy except undefinedStack Overflow