我有一系列对象,例如
TimeSpan
我需要一个lodash表达式,它将根据一个属性生成一组唯一对象。例如,如果我使用名字,它会给我这三个:
[{ "name": "Jen", "age":31, "eyecolor": "blue", "hair":"brown"},
{ "name": "Jen", "age":32, "eyecolor": "green", "hair":"blonde"},
{ "name": "Jules", "age":31, "eyecolor": "blue", "hair":"brown"}, ,
{ "name": "Brian", "age":40, "eyecolor": "blue", "hair":"brown"}]
答案 0 :(得分:10)
对于Lodash版本4+使用_.uniqBy()
:
var arr = [{"name":"Jen","age":31,"eyecolor":"blue","hair":"brown"},{"name":"Jen","age":32,"eyecolor":"green","hair":"blonde"},{"name":"Jules","age":31,"eyecolor":"blue","hair":"brown"},{"name":"Brian","age":40,"eyecolor":"blue","hair":"brown"}];
var unique = _.uniqBy(arr, 'name');
console.log(unique);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
对于4岁以下的Lodash版本,请使用_.uniq()
:
var arr = [{"name":"Jen","age":31,"eyecolor":"blue","hair":"brown"},{"name":"Jen","age":32,"eyecolor":"green","hair":"blonde"},{"name":"Jules","age":31,"eyecolor":"blue","hair":"brown"},{"name":"Brian","age":40,"eyecolor":"blue","hair":"brown"}];
var unique = _.uniq(arr, 'name');
console.log(unique);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>
答案 1 :(得分:1)
如果你的lodash版本高于4.0,你应该使用_.uniqBy()
。
此时,_.uniq()
不起作用,它只接受一个参数,该参数无法处理迭代的对象。
var arr = [{ "name": "Jen", "age":31, "eyecolor": "blue", "hair":"brown"},
{ "name": "Jen", "age":32, "eyecolor": "green", "hair":"blonde"},
{ "name": "Jules", "age":31, "eyecolor": "blue", "hair":"brown"},
{ "name": "Brian", "age":40, "eyecolor": "blue", "hair":"brown"}];
var result = _.uniqBy(arr, 'name');
console.log(result)
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;