JavaScript从对象数组中获取键数组

时间:2017-08-03 20:24:45

标签: javascript lodash

我有这个数组,数组中的每个对象只有一个键:

[{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }]

我想将所有键提取到一个数组中,以便我想要的结果是:

["hello", "there", "everybody"]

在Lodash或vanilla JavaScript(最好是ES6)中,这是一种简洁的方法吗?

6 个答案:

答案 0 :(得分:5)

您可以将Object.keyslet arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }]; let keys = [].concat(...arr.map(Object.keys)); console.log(keys);一起使用。



editing




答案 1 :(得分:5)

使用Object#assign合并到单个对象,并使用Object#keys从对象中检索键:

const arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];

const keys = Object.keys(Object.assign({}, ...arr));

console.log(keys);

ES5版本使用lodash的_.assign()_.spread()合并为一个对象,_.keys()来获取密钥:

var arr = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];

var keys = _.keys(_.spread(_.assign)(arr))

console.log(keys);
    
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 2 :(得分:3)

您可以将数组map与对象keys结合使用:

const array = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];

const result = array.map((el) => Object.keys(el)[0]);

答案 3 :(得分:1)

&#13;
&#13;
var x = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];

console.log(x.map(function(obj){return Object.keys(obj)[0]}));
&#13;
&#13;
&#13;

答案 4 :(得分:1)

以下是使用lodash的flatMap

的解决方案
let result = _.flatMap(data, _.keys);

答案 5 :(得分:1)

保留重复键的本机ES5解决方案将是:

var objects = [{ "hello": "value1" }, { "there": "value2" }, { "everybody": "value3" }];
var keys = [];
for (var obj in objets) {
    keys.push(Object.keys(obj)[0]);
}