nehel
nehel

Reputation: 885

Map through array of objects even through objects that don't have one or two keys compared to other objects

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
  }
]

Upvotes: 0

Views: 64

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

Instead of gussing the keys that an object could have, you can use Object.keys or a for...in loop to dynamically get or loop through keys of an object. Like this:

var obj = {
  "key1": 2,
  "key2": 3,
  "key-unknown": 5
}

console.log("METHOD 1:");
var keys = Object.keys(obj);
console.log("obj has these keys: ", keys);

console.log("\nMETHOD 2:");
for(var key in obj) {
  console.log("'" + key + "' is a key");
}

Using the above two methods you can safely and dynamically use only the keys that the object has and not use a set of predefined static keys that may or may not be in the object and that could be fewer than what the object actually has.

Upvotes: 1

Redu
Redu

Reputation: 26191

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))

Upvotes: 0

Related Questions