简体   繁体   中英

Underscore.js - get unique property values

I only recently discovered the power of underscore.js, still new to the methods I kindly ask for a suggestion:

How do I get from this:

[
    [{
        "name": "Type 2",
        "id": 14
    }],
    [{
        "name": "Type 1",
        "id": 13
    }, {
        "name": "Type 3",
        "id": 15
    }],
    [{
        "name": "Type 2",
        "id": 14
    }],
    [{
        "name": "Type 1",
        "id": 13
    }]
]

to this:

["Type 1","Type 2","Type 3"]

ie no duplicated and "name" property only.

Any suggestions much appreciated.

_(data).chain().flatten().pluck('name').unique().value()

(将嵌套列表转换为平面列表,从列表中的每个对象中选择name ,并使其唯一。)

  • Use flatten first, to convert the nested array to a flat array.
  • Then pluck to get the "name" values as an array
  • Finally uniq

_.uniq(_.pluck(_.flatten(items), "name"))

Fiddle

var arr = _.uniq(_.map(_.flatten(array), function(e) {
    return e.name;
}));
_.uniq(_.pluck(x,'name'));

上面的代码足以提取不同的“名称”属性

Simple way:

1. use _.map to get all the names

var names = _.map(items, function(item) { return item.name});

2. Get the _.uniq from that names

var uniqueNames = _.uniq(names);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM