Underscore.js - get unique property values

后端 未结 5 1978
我寻月下人不归
我寻月下人不归 2021-02-13 18:12

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:

[
    [{
                 


        
相关标签:
5条回答
  • 2021-02-13 18:18
    _(data).chain().flatten().pluck('name').unique().value()
    

    (Convert the nested lists to a flat one, pick name from each of the objects in the list, and make it unique.)

    0 讨论(0)
  • 2021-02-13 18:24
    • 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

    0 讨论(0)
  • 2021-02-13 18:24

    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);
    0 讨论(0)
  • 2021-02-13 18:37
    _.uniq(_.pluck(x,'name'));
    

    the above code is sufficient for extracting different "name" attribute

    0 讨论(0)
  • 2021-02-13 18:41
    var arr = _.uniq(_.map(_.flatten(array), function(e) {
        return e.name;
    }));
    
    0 讨论(0)
提交回复
热议问题