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" ]
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" ]
Underscore solution:
_.chain(xs).map(_.keys).flatten().unique().value();
Demo: http://jsbin.com/vagup/1/edit
Another option:
keys = _.keys(_.extend.apply({}, array))
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));
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);