Retrieving the keyword list of the JavaScript vol object. 2

Here's the original question: Getting a list of JavaScript keywords

But if the situation is a little more complicated than:

var obj = [
   { key1: 'value1' },
   { key2: 'value2' },
   { key3: 'value3' },
   { key4: 'value4' }
]

Then how do you get such keys?

[key1,key2,key3,key4]
+6
source share
6 answers

You can use a combination of Object.keysand Array#map.

let obj = [
   { key1: 'value1' },
   { key2: 'value2' },
   { key3: 'value3' },
   { key4: 'value4' },
];

let keys = [].concat(...obj.map(Object.keys));

console.log(keys);
Run codeHide result
+15
source

you can get the keys for each object in obj and then use concat()to add it to the 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);
Run codeHide result
+7
source

Array#reduce.

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);
Hide result
+5

Array#reduce() Object.keys().Reduce forEach Object

var obj = [ { key1: 'value1' }, { key2: 'value2' }, { 
key3: 'value3' }, { 
key4: 'value4' } ]


console.log(obj.reduce(function(a,b){
 Object.keys(b).forEach(function(val){
   a.push(val)
  })
  return a;
},[]))
Hide result
+1

You can iterate over the properties of an object using for , something like this.

var obj = [
   { key1: 'value1' },
   { key2: 'value2' },
   { key3: 'value3' },
   { key4: 'value4' }
],
keysArray = [];

obj.forEach((item)=>{
    for(key in item){
      keysArray.push(key);
    }
});
    
console.log(keysArray);
Run codeHide result
+1
source

Using Arrows looks a bit strange due to [0]: /

var obj = [
   { key1: 'value1' },
   { key2: 'value2' },
   { key3: 'value3' },
   { key4: 'value4' }
];

var result = obj.map(x => Object.keys(x)[0]);

console.log(result);
Run codeHide result

And if there is a pair of keys with one key, then

obj.map(Object.keys).reduce((a, b) => a.concat(b));

Other methods:

[].concat(...obj.map(Object.keys));

[].concat.apply(this, obj.map(Object.keys));

Or using Lodash (which I use a lot)

_.flatten(obj.map(Object.keys))
0
source

All Articles