<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
There is a one line solution
ReplyDeleteconst commonKeys = Array.from(new Set([...Object.keys(obj1), ...Object.keys(obj2)]))