gpt4 book ai didi

javascript - lodash 基于属性的唯一性

转载 作者:行者123 更新时间:2023-12-04 09:46:14 25 4
gpt4 key购买 nike

我有一系列对象,例如

[{ "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"}]

我需要一个 lodash 表达式,它会产生一组基于一个属性的唯一对象。例如,如果我使用名称,它会给我这三个:
[{ "name": "Jen", "age":31, "eyecolor": "blue", "hair":"brown"}, 
{ "name": "Jules", "age":31, "eyecolor": "blue", "hair":"brown"},
{ "name": "Brian", "age":40, "eyecolor": "blue", "hair":"brown"}]

最佳答案

对于 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>

关于javascript - lodash 基于属性的唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33790019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com