lodash uniq-选择要保留在对象数组中的重复对象 [英] lodash uniq - choose which duplicate object to keep in array of objects
问题描述
有任何方法可以基于非空键来指定要保留的数组项.似乎uniq只会保留第一次出现.
is there any way to specify which array item to keep based on a key being non-empty. it seems uniq just keeps the first occurrence.
例如:
var fruits = [
{'fruit': 'apples', 'location': '', 'quality': 'bad'},
{'fruit': 'apples', 'location': 'kitchen', 'quality': 'good'},
{'fruit': 'pears', 'location': 'kitchen', 'quality': 'excellent'},
{'fruit': 'oranges', 'location': 'kitchen', 'quality': ''}
];
console.log(_.uniq(fruits, 'fruit'));
/* output is:
Object { fruit="apples", quality="bad", location=""}
Object { fruit="pears", location="kitchen", quality="excellent"}
Object { fruit="oranges", location="kitchen", quality=""}
*/
有什么办法告诉lodash uniq选择具有位置值的重复项吗?它保留的是坏苹果而不是好苹果.
Is there any way to tell lodash uniq to choose the duplicate that has a location value ? It's keeping the bad apples instead of the good apples.
~~~
我的最终解决方案是在uniq中使用sortByOrder
My final solution was using sortByOrder inside uniq
console.log(_.uniq(_.sortByOrder(fruits, ['fruit','location'], ['asc','desc']),'fruit'))
导致:
Object { fruit="apples", location="kitchen", quality="good"}
Object { fruit="oranges", location="kitchen", quality=""}
Object { fruit="pears", location="kitchen", quality="excellent"}
推荐答案
从我在 https://lodash.com/docs#uniq 无法指定.您可能想要做的是一组水果,然后您可以选择所需的质量.这取决于上下文以及您为什么需要它.
From what I see in docs at https://lodash.com/docs#uniq there is no way to specify that. Probably what you want to do is a groupBy fruit and then you can choose what quality you need. It depends on context and why you need it.
您能再解释一下您的问题吗?
Can you explain your problem a little more?
这篇关于lodash uniq-选择要保留在对象数组中的重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!