admin管理员组文章数量:1297125
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" ]
Share
edited May 12, 2014 at 7:35
Himanshu
4,39516 gold badges33 silver badges39 bronze badges
asked May 12, 2014 at 7:32
SatoSato
8,62219 gold badges72 silver badges123 bronze badges
4 Answers
Reset to default 6Another option:
keys = _.keys(_.extend.apply({}, array))
Underscore solution:
_.chain(xs).map(_.keys).flatten().unique().value();
Demo: http://jsbin./vagup/1/edit
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 bines 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);
本文标签: javascriptHow to get the unique keys of an array of object by underscoreStack Overflow
版权声明:本文标题:javascript - How to get the unique keys of an array of object by underscore? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741646664a2390222.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论