Lodash。除了未定义

时间:2017-05-24 09:17:49

标签: javascript lodash

尝试将对象数组分组以使用Lodash

获取唯一属性

但如果属性不存在,它需要undefined类似于唯一属性

有没有办法避免它?并只留下现有的属性?

所以我只会实现My Office 1,但我的解决方案会得到 undefinedMy Office 1 示例数组

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

Object.keys(_.groupBy(arr, 'office.name')).map((office, index) { ... }

1 个答案:

答案 0 :(得分:3)

您可以过滤掉没有路径的对象。



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>
&#13;
&#13;
&#13;