Last active
June 19, 2023 10:08
-
-
Save asif-jalil/dd155e99e6674f5aac5acc4afd6ecffa to your computer and use it in GitHub Desktop.
If you need to find specific key/value from a array of object or object of object (i,e multi level nested object), you can use this function. That's preety cool.
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 { isObject } from "lodash"; | |
| export default function filterNestedObject(object, keyToFind, valToFind) { | |
| if (!isObject(object)) { | |
| return []; | |
| } | |
| const keys = Object.keys(object); | |
| return keys | |
| .map(key => { | |
| if (key === keyToFind && object[key] === valToFind) { | |
| return object; | |
| } | |
| if (Array.isArray(object[key])) { | |
| return object[key] | |
| .map(obj => filterNestedObject(obj, keyToFind, valToFind)) | |
| .flat() | |
| .filter(obj => !!obj); | |
| } | |
| if (isObject(object[key])) { | |
| return filterNestedObject(object[key], keyToFind, valToFind); | |
| } | |
| return false; | |
| }) | |
| .flat() | |
| .filter(obj => !!obj); | |
| } |
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 object = { | |
| schemaVersion: 15, | |
| body: { | |
| id: "cnWNPmSTDG", | |
| rows: [ | |
| { | |
| id: "tyrtnyEeRX", | |
| columns: [ | |
| { | |
| id: "oswmB3BZoE", | |
| contents: [ | |
| { | |
| id: "L_YoZhqJ7L", | |
| type: "heading", | |
| values: { | |
| fontSize: "22px", | |
| linkStyle: { | |
| linkColor: "#0000ee" | |
| }, | |
| displayCondition: null | |
| } | |
| }, | |
| { | |
| id: "XHWYbiN6Su", | |
| type: "form", | |
| values: { | |
| action: { | |
| method: "POST", | |
| url: "https://mailbluster.com" | |
| }, | |
| fields: [ | |
| { | |
| name: "email", | |
| label: "Email address", | |
| type: "email", | |
| required: true | |
| }, | |
| { | |
| type: "checkbox", | |
| name: "consent", | |
| label: "Consent", | |
| required: true | |
| } | |
| ] | |
| } | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| } | |
| filterNestedObject(object, "type", "checkbox"); | |
| // expected output | |
| // [ | |
| // { | |
| // type: 'checkbox', | |
| // name: 'consent', | |
| // label: 'Consent', | |
| // options: 'I agree to your terms and condition', | |
| // placeholder_text: 'Consent', | |
| // show_label: false, | |
| // required: true, | |
| // meta_data: {} | |
| // } | |
| // ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment