-1

So if I have a JSON file with n number of objects in it, each of them having n number of properties, and two of the objects having one property in common, is there a way to, in an external JavaScript file, check to see which two objects in the JSON file have a property in common. To take it a step further, is there a way to then see if there are more properties in common between these two? I did research and found nothing on this exact topic, only a post about checking to see if a given object has a given property in it.

Thanks a lot if you can help!

Jodast
  • 1,279
  • 2
  • 18
  • 33
  • 2
    What have you tried? Do you have any code you've been working on? – Geuis Jul 22 '18 at 00:51
  • 1
    @Geuis I haven't tried anything because I have no clue as to where I should start. I have my code here: https://glitch.com/edit/#!/petal-canid?path=app.js:160:64 – Jodast Jul 22 '18 at 00:54

1 Answers1

2

You could try object.keys() and filter the array based on the common properties. Please check browser compatibility of Object.keys() before using.

var obj1 = {
name:'hello',
age:12,
fav: 'fav',
foo: 'foo'
}

var obj2 = {
name: 'hey',
say: 'say',
prop: 'prop',
top: 'top'
}

var common = Object.keys(obj1).filter(obj1item =>  Object.keys(obj2).indexOf(obj1item) !== -1 );

console.log(common);

Object.keys() returns an array of properties. We are comparing both the arrays for common properties.

Object.keys(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Array.filter(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

samuellawrentz
  • 1,662
  • 11
  • 23