Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,5 @@ This is a tiny library of javascript functions, currently comprising:
- isEqual
- inPlaceShuffle
- regularShuffle
- checkNested

35 changes: 35 additions & 0 deletions src/checkNested.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* A function to deeply compare objects
* @param {Object} obj - Object to examine
* @param {String} key you are searching for
* @return {Boolean}
*/

const checkNested = (object, searchKey) => {
// If bad input, return false:
if (object === null || object === undefined) {
return false;
}

for (let key of Object.keys(object)) {
// Iterate through keys for match:
if (key === searchKey) {
return true;
} else {
const aNestedObject = object[key];

// If key isn't a match, try to see if the key's value is an object.
// if it is, we need to search through it's keys:
if (typeof aNestedObject === 'object') {
// We can recursively search for our searchKey in
// nested value, passing in objectSubKey (nested object) this time:
if (checkNested(aNestedObject, searchKey) === true) {
return true;
}
}
}
}
return false;
};

module.exports = checkNested;
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export { default as peek } from './peek.js';
export { default as sieveOfE } from './sieveOfE.js';
export { default as sort } from './sort.js';
export { default as camelCase } from './camelCase.js';
export { default as checkNested } from './checkNested';
export { default as isEqual } from './isEqual';
export { default as inPlaceShuffle } from "./inPlaceShuffle.js";
export { default as regularShuffle } from "./regularShuffle.js";
Expand Down
27 changes: 27 additions & 0 deletions src/tests/checkNested.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
const expect = require('chai').expect;
const checkNested = require('../').checkNested;

describe('checkNested', () => {
it('returns true if object contains search key', () => {
const object = {
name: {
first: 'Pete',
favorite: {
color: 'blue',
},
},
};
expect(checkNested(object, 'favorite')).to.equal(true);
});
it('returns false if object does not contain search key', () => {
const object = {
name: {
first: 'Pete',
favorite: {
color: 'blue',
},
},
};
expect(checkNested(object, 'movie')).to.equal(false);
});
});