1

I have a few objects:

var a = { "abc": {}, "def": {}, "ghi": {} };
var b = { "abc": {}, "ghi": {}, "jkl": {}, "mno": {} };
var c = { "abc": {}, "ghi": {}, "xyz": {}, "mno": {} };

And I wonder how to get the property names that exist in all of them:

var d = getOmniPresentProperties(a, b, c);

function getOmniPresentProperties() {
  // black magic?
}

so d should be ["abc", "ghi"]

The number of arguments/ objects to compare may vary so I am unsure how to approach. Any ideas?

Alex
  • 9,911
  • 5
  • 33
  • 52
  • I suggest you write down, in English, how would solve this problem, as if you were explaining it to someone. Then take your description and convert it into JavaScript. By the way, your problem is precisely isomorphic to saying "given a list of lists, how to return only those elements that exist in all lists". Your problem can be converted into that one by taking arrays (lists) of the keys of each object. –  Feb 22 '17 at 11:44
  • *The number of arguments/ objects to compare may vary* Yes, computers do find it difficult to deal with variable numbers of things. However, remember that if you define the operation you are interested in as `I(o1, o2)`, then `I(o1, o2, o3)` is the same as, and can be implemented as, `I(o1, I(o2, o3))`. –  Feb 22 '17 at 11:49
  • its not a dublicate... the linked question has a list of 2, while i need to check against n – Alex Feb 22 '17 at 11:54
  • The concept is the same. To find the keys in common in objects O1, O2, and O2, find the keys in common in O1 and O2, and then find the keys in common with O3. –  Feb 22 '17 at 14:03

1 Answers1

6

Use Array#filter method to filter out values.

var a = { "abc": {}, "def": {}, "ghi": {} };
var b = { "abc": {}, "ghi": {}, "jkl": {}, "mno": {} };
var c = { "abc": {}, "ghi": {}, "xyz": {}, "mno": {} };

var d = getOmniPresentProperties(a, b, c);


function getOmniPresentProperties(...vars) {
  return Object.keys(vars[0]) // get object properties of first array
    .filter(function(k) { // iterate over the array to filter out
      return vars.every(function(o) { // check the key is ehist in all object
        return k in o;
      })
    })
}

console.log(d);

ES5 version

You can fetch keys from all object and

function getOmniPresentProperties(a,b,c) {
  return Object.keys(a).filter(function(key){
    return key in a && key in b && key in c
  })
}

var a = { "abc": {}, "def": {}, "ghi": {} };
var b = { "abc": {}, "ghi": {}, "jkl": {}, "mno": {} };
var c = { "abc": {}, "ghi": {}, "xyz": {}, "mno": {} };

var d = getOmniPresentProperties(a, b, c);
console.log(d)
Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188