2

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 Answers 4

6

Another option:

keys = _.keys(_.extend.apply({}, array))
Sign up to request clarification or add additional context in comments.

Comments

4

Underscore solution:

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

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

Comments

2

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));

1 Comment

Hey man, you shouldn't downvote a perfectly working solution! Ask for details, I'll do it anyways. Plus flag it to delete? Srsly...
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.