Last active
April 13, 2017 06:25
-
-
Save mgtitimoli/5199b6c02d0974da16a2436eba01d7ca to your computer and use it in GitHub Desktop.
Checks recursively if an object contains another
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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