Getting JavaScript object key list vol. 2
You can use mix of Object.keys
and Array#flatMap
.
let obj = [
{ key1: 'value1' },
{ key2: 'value2' },
{ key3: 'value3' },
{ key4: 'value4' },
];
let keys = obj.flatMap(Object.keys);
console.log(keys);
you can get keys for each object in obj and then use concat()
to add it to your result array.
var obj = [
{
key1: 'value1'
},
{
key2: 'value2'
},
{
key3: 'value3'
},
{
key4: 'value4'
}
]
var keyList = [];
obj.forEach(function(o){
keyList = keyList.concat(Object.keys(o));
});
console.log(keyList);
You can achieve it using Array#reduce
method.
var obj = [{
key1: 'value1'
}, {
key2: 'value2'
}, {
key3: 'value3'
}, {
key4: 'value4'
}];
var res = obj
// iterate over the array
.reduce(function(arr, o) {
// get keys and push into the array
[].push.apply(arr, Object.keys(o));
// return the araray reference
return arr;
// set initial value as an empty array
}, []);
console.log(res);
// ES6 alternative
var res1 = obj.reduce((arr, o) => (arr.push(...Object.keys(o)), arr), []);
console.log(res1);