Dylan
Dylan

Reputation: 1348

How to tell if all value of object is present in another object

I want to doSomething if all the value of object is present in another object

  const object1 = { letter: 'a', number: 1 };
  const object2 = { letter: 'b', number: 2 };
  const object3 = { letter: 'a', number: 1, address: 'not in object4' }
  const object4 = { letter: 'a', number: 1, address: 'different address', section: 'abc' }

  if (isPresent(object1, object4)) doSomething;

If I replace the object1 with object2 or object3 in isPresent first argumet, it should return false because object4 doesn't have their values, and return true if all the value on argument1 is present on argument2 like on the sample.

Upvotes: 1

Views: 66

Answers (2)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

Try this:

  
  
const object1 = { letter: 'a', number: 1 };
const object2 = { letter: 'b', number: 2 };
const object3 = { letter: 'a', number: 1, address: 'not in object4' }
const object4 = { letter: 'a', number: 1, address: 'different address', section: 'abc' }

function isPresent(v1, v2) {
  v2 = JSON.stringify(v2);
  v1 = JSON.stringify(v1).slice(1, -1);
  return v2.includes(v1);
}

console.log(isPresent(object1, object4)); //  true
console.log(isPresent(object2, object4)); // false
console.log(isPresent(object3, object4)); // false

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

You could get all entries and check against the other object.

const
    isPresent = (a, b) => Object.entries(a).every(([k, v]) => k in b && v === b[k]),
    object1 = { letter: 'a', number: 1 },
    object2 = { letter: 'b', number: 2 },
    object3 = { letter: 'a', number: 1, address: 'not in object4' },
    object4 = { letter: 'a', number: 1, address: 'different address', section: 'abc' };

console.log(isPresent(object1, object4)); //  true
console.log(isPresent(object2, object4)); // false
console.log(isPresent(object3, object4)); // false

Upvotes: 3

Related Questions