Skip to content

Instantly share code, notes, and snippets.

@mgtitimoli
Last active April 13, 2017 06:25
Show Gist options
  • Save mgtitimoli/5199b6c02d0974da16a2436eba01d7ca to your computer and use it in GitHub Desktop.
Save mgtitimoli/5199b6c02d0974da16a2436eba01d7ca to your computer and use it in GitHub Desktop.
Checks recursively if an object contains another
const {hasOwnProperty} = Object.prototype;
const isObject = thing => thing !== null && typeof thing === "object";
const objectContains = (object, otherObject) => {
const objectIsArray = Array.isArray(object);
const otherObjectIsArray = Array.isArray(otherObject);
if (objectIsArray && !otherObjectIsArray) {
return false;
}
if (otherObjectIsArray && !objectIsArray) {
return false;
}
return Object.entries(otherObject).every(([otherKey, otherValue]) => {
if (!hasOwnProperty.call(object, otherKey)) {
return false;
}
const value = object[otherKey];
if (!isObject(otherValue)) {
return value === otherValue;
}
return objectContains(value, otherValue);
});
};
export default objectContains;
import objectContains from "./objectContains";
console.log(objectContains({}, {})); // true: both are objects
console.log(objectContains({}, [])); // false: types differ (one is an object and the other is an array)
console.log(objectContains([], {})); // false: types differ (one is an array and the other is an object)
console.log(objectContains([], [])); // true: both are arrays
const o1 = {k1: {k2: true}};
console.log(objectContains(o1, {})); // true: no entry to check
console.log(objectContains(o1, {k1: {}})); // true: k1 matches with no entry to check
console.log(objectContains(o1, {k1: {k2: true}})); // true: [k1, k2] paths matches
console.log(objectContains(o1, {k3: 10})); // false: k3 is not in o1
console.log(objectContains(o1, {k1: {k3: 10}})); // false: k1 does not contain a k3 entry
console.log(objectContains(o1, {k1: {k2: false}})); // false: [k1, k2] path values differ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment