Thursday, August 8, 2019

[JavaScript][Resolved] Get common keys of objects

<script>
var obj1 = {
  a:1,
  b:2
}
var obj2 = {
  c:1,
  a:2
}
var commonKeys = combineObjectsKeys(obj1,obj2);
function combineObjectsKeys(obj1,obj2){
  var keys   = [],
      result = [];
  keys.push(Object.keys(obj1));
  keys.push(Object.keys(obj2));
  for(var i=0; i<keys[0].length;i++){
    if(!(result.indexOf(keys[0][i]) > -1)) 
        result.push(keys[0][i]);
    }
    for(var j=0; j<keys[1].length;j++){
      if(!(result.indexOf(keys[1][j]) > -1))
        result.push(keys[1][j]);
    }
  }
  return result.sort();
}
console.log(commonKeys);
</script>

Result :
 Reference:
https://stackoverflow.com/questions/57343261/compare-2-object-by-keys/57343334

1 comment :

  1. There is a one line solution

    const commonKeys = Array.from(new Set([...Object.keys(obj1), ...Object.keys(obj2)]))

    ReplyDelete