Get unique keys from multiple objects

后端 未结 3 380
不思量自难忘°
不思量自难忘° 2020-12-11 12:45

If I have an array of objects like this:

var mountains = [
    { name: \'Kebnekaise\', elevation: 2106 },
    { name: \'Mount Ngauruhoe\', elevation: 2291, c         


        
3条回答
  •  时光说笑
    2020-12-11 13:19

    You could iterate over the array of objects and iterate over each element's keys with Object.keys(obj), adding them to a hash to avoid duplicates:

    function getKeySet (data) {
      var keys = {};
    
      data.forEach(function (datum) {
        Object.keys(datum).forEach(function (key) {
          keys[key] = true;
        });
      });
    
      return Object.keys(keys);
    }
    

    Alternately you could add all the keys to an array and filter out duplicates. Either way this will be O(nm) where n is the number of elements in the array and m is the average number of keys.

提交回复
热议问题