Map through an array of objects, even through objects that do not have one or two keys compared to other objects

advertisements

Title. I can have two or three types of objects, but i would like to make reliable function to cover all other cases if any new keys/properties will be added to future objects.

Whenever i'm mapping through objects with the same properties (obj1, obj4) everything is K. The problem is when i want to make a function to map through all objects in arr with keys that may or may not be in particular object.

I was thinking about if ('key' in obj) but that wouldn't make function reliable for future, if new keys might be added unless I could analyze all object keys in arr, by creating new array with unique key objects. But if object will have 10 keys and there will be 1000+ objects in an array I assume there will be performance issues; correct me if i'm wrong.

Same goes for .hasOwnProperty().

const arr = [
  obj1 = {
    key1: val1,
    key2: val2,
    key3: val3
  },
  obj2 = {
    key3: val3
  },
  obj3 = {
    key1: val4,
    key2: val5,
    key3: val1
  },
  obj4 = {
    key1: val6,
    key2: val7
  }
]


From a wild guess you may be in need of a function such as;

function fillMissingKeys(a){
  var keys = a.reduce((k,o) => Object.assign(k,Object.keys(o)),[])
              .reduce((o,k) => (o[k] = null,o),{});

  return a.map(o => Object.assign({},keys,o));
}

var arr = [
  obj1 = {
    key1: "val1",
    key2: "val2",
    key3: "val3"
  },
  obj2 = {
    key3: "val3"
  },
  obj3 = {
    key1: "val4",
    key2: "val5",
    key3: "val1",
    key4: "val8"
  },
  obj4 = {
    key1: "val6",
    key2: "val7"
  }
];

console.log(fillMissingKeys(arr))