Lodash Javascript 基于唯一属性值返回元素

Lodash Javascript Return Elements Based Of Off Unique Property Values

本文关键字:属性 返回 元素 唯一 Javascript 于唯一 Lodash      更新时间:2023-09-26

我正在尝试使用 lodash,但找不到一个 javascript 函数可以接受这个:

[
{item: {id: 1}, 'name': 'hi'},
{item: {id: 2}, 'name': 'hey'},
{item: {id: 1}, 'name': 'hello'}
];

并将其变成

[
{item: {id: 1}, 'name': 'hi'},
{item: {id: 2}, 'name': 'hey'}
];

到目前为止,我在javascript中有这个:

var mainThings = [
        {item: {id: 1}, 'name': 'hi'},
        {item: {id: 2}, 'name': 'hey'},
        {item: {id: 1}, 'name': 'hello'}
        ];
uniqueMainsFunc = function() {
    var ids = [],
        mains = [];
    _.forEach(mainThings, function(thing) {
        if (ids.indexOf(thing.item.id) === -1) {
            ids.push(thing.item.id);
            mains.push(thing);
        }
    });
    return uniqueMains;
};

在这种情况下,uniqueMains 将仅包含:

[
{item: {id: 1}, 'name': 'hi'},
{item: {id: 2}, 'name': 'hey'}
]

有没有一个lodash函数可以更好地处理这个问题?在.forEach之后,我尝试使用!_.some(uniqueNestedIds,thing.item.id),但它不起作用。

uniqBy 方法可以解决你的问题

var mainThings = [
    { item: { id: 1 }, 'name': 'hi' },
    { item: { id: 2 }, 'name': 'hey' },
    { item: { id: 1 }, 'name': 'hello' }
];

var uniq = _.uniqBy(mainThings, 'item.id')
console.log(uniq);

结果:

[ { item: { id: 1 }, name: 'hi' },
  { item: { id: 2 }, name: 'hey' } ]

您可以使用_.uniqBy来实现此目的:

_.uniqBy(mainThings, function(item) {
    return item.item.id;
});

请参阅此 Plnkr。