Created
March 7, 2020 11:04
-
-
Save Tiim/ae6765212ebff26834014e01cb2c4ccc to your computer and use it in GitHub Desktop.
Query Inside JS object like lodash _.get but handles arrays as well
This file contains 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
function queryObject(object, path) { | |
const parts = path.split('.'); | |
let objects = wrapArray(object); | |
while (parts.length > 0 && objects.length > 0) { | |
const prop = parts.shift(); | |
objects = objects | |
.flatMap((o) => wrapArray(o[prop])) | |
.filter((o) => o != null); | |
} | |
return objects; | |
} | |
function containsArray(object, path) { | |
if (object == null) { | |
return null; | |
} | |
if (Array.isArray(object)) { | |
return true; | |
} | |
const parts = path.split('.'); | |
while (parts.length > 0) { | |
const prop = parts.shift(); | |
object = object[prop]; | |
if (Array.isArray(object)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
function wrapArray(obj) { | |
if (Array.isArray(obj)) { | |
return obj; | |
} else { | |
return [obj]; | |
} | |
} | |
module.exports = { queryObject, containsArray }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment