javascript - Intersection of an arbitrary number of objects -


i trying find, efficiently possible, intersection between arbitrary number of objects. objects contain other sub-objects, each sub-object being stored under unique key on parent. purposes safe assume when comparing sub-object on object 1 sub-object on object 2, contents same not care if 1 overwrites other. far solution working with, afraid not efficient enough:

function intersectobjects(...objects){   /*note: function overwrite values on duplicate keys*/   var returnobj; //temp variable store return value   objects.foreach((obj, i) => {     //on first loop store object     if (i == 0) returnobj = obj;     else {       //get array of properties being returned       const returnprops = object.getownpropertynames(returnobj);       //loop on properties array       returnprops.foreach((propkey, j) => {         //if current property not exist on return object         //then delete property on return object         if(!obj[returnprops[j]]) delete returnobj[returnprops[j]];       });     }   });   return returnobj; } 

is there more efficient solution this? there library handles function , functions efficiently? there function not aware of? answers of these questions appreciated.

you use es6 function, not mutate of input objects, returns new one:

function intersectobjects(...objects) {      return !objects.length ? {}           : object.assign(...object.keys(objects[0]).filter(                  key => objects.every( o => key in o )             ).map( key => ({ [key]: objects[0][key]}) ));  }    // sample run  var data = [      { a: 1, b: 2, c: 3, d: 4, e: 5},      {       b: 2, c: 3, d: 4, e: 5, f: 6},      { a: 1, b: 2,       d: 4, e: 5},      { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7}  ];  var result = intersectobjects(...data);  console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

note executing delete on object costly operation, , cripples optimisation engines can otherwise seek , apply.


Comments