尝试将对象数组分组以使用Lodash
获取唯一属性但如果属性不存在,它需要undefined
类似于唯一属性
有没有办法避免它?并只留下现有的属性?
所以我只会实现My Office 1
,但我的解决方案会得到
undefined
和My Office 1
示例数组
[
{office: null},
{office:
{
name: 'My Office 1'
}
}
]
码
Object.keys(_.groupBy(arr, 'office.name')).map((office, index) { ... }
答案 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;