使用lodash获取uniq嵌套对象数组

Foo*_*ion 7 javascript lodash

我的数据有带有数组的嵌套对象。我想让嵌套对象属性在输出中是唯一的。目前我正在使用上面的lodash v4,我找到了一个合适的解决方案,但仅适用于lodash v3。

数据

[{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
},
{
   menu: { id: 1 },
   other: { data: "another1" }
}]
Run Code Online (Sandbox Code Playgroud)

预期产出

[{
   menu: { id: 1 },
   other: { data: "another1" }
},
{
   menu: { id: 2 },
   other: { data: "another2" }
}]
Run Code Online (Sandbox Code Playgroud)

类似的 lodash v3 解决方案在这里。v4的解决方案是什么?只要代码运行得更快、更简单,不使用 lodash 的解决方案仍然可以接受。

Tus*_*har 7

您可以使用uniq如下方法。

var arr = [{
  menu: {
    id: 1
  }
}, {
  menu: {
    id: 2
  }
}, {
  menu: {
    id: 1
  }
}];

var unique = _.uniq(arr, 'menu.id');
console.log(unique);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)


对于 lodash 4.xx,使用uniqBy

var arr = [{
  menu: {
    id: 1
  },
  other: {
    data: "another1"
  }
}, {
  menu: {
    id: 2
  },
  other: {
    data: "another2"
  }
}, {
  menu: {
    id: 1
  },
  other: {
    data: "another1"
  }
}];

console.log(_.uniqBy(arr, 'menu.id'));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Run Code Online (Sandbox Code Playgroud)