How to get the unique keys of an array of object b

2019-05-22 15:30发布

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" ]

4条回答
放荡不羁爱自由
2楼-- · 2019-05-22 16:09

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);
查看更多
Summer. ? 凉城
3楼-- · 2019-05-22 16:10

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楼-- · 2019-05-22 16:14

Another option:

keys = _.keys(_.extend.apply({}, array))
查看更多
劫难
5楼-- · 2019-05-22 16:27

Underscore solution:

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

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

查看更多
登录 后发表回答