How to get the unique keys of an array of object by underscore?

大憨熊 提交于 2019-12-07 19:09:09

问题


I have an array of object, and want to get the unique keys by underscore, how can I do that?

Array[ Object{a: 1, b: 2}, Object{b: 3, c: 4, d: 5} ]

I want to get:

Array[ "a", "b", "c", "d" ]

回答1:


Underscore solution:

_.chain(xs).map(_.keys).flatten().unique().value();

Demo: http://jsbin.com/vagup/1/edit




回答2:


Another option:

keys = _.keys(_.extend.apply({}, array))



回答3:


Pure ES6 solution using Spread operator.

Object.keys({...objA, ...objB});

Background

It takes the properties of the items (objA, objB) and "unwraps" them, then it combines these properties into a single object (see { }). Then we take the keys of the result.

TypeScript transpile output (ES5):

// Helper function
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};

// Compile output
// Note that it's NOT lodash or underscore but the helper function from above
Object.keys(__assign({}, objA, objB));



回答4:


Use _.keys() to get all keys in the object

var result = [];
_.each(obj, function(prop){
   var temp = _.keys(prop);
   _.each(temp, function(value){
      result.push(value);
   })
});
console.log(result);

_.contains([],value) checks value is exiting in the array or not and return 'true', if it exists; 'false', otherwise.The following is for eliminating duplicated keys and then pushes keys to result array.

var result = [];
_.each(obj, function(prop){
    var temp = _.keys(prop);
    _.each(temp, function(value){
       var flag = _.contains(result, value);
       if(!flag){
         result.push(value);
       }
    });
});
console.log(result);


来源:https://stackoverflow.com/questions/23603364/how-to-get-the-unique-keys-of-an-array-of-object-by-underscore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!