Created
January 22, 2022 20:12
-
-
Save OliverMax/9fdf0f70f99ded43c2147c836a328d0a to your computer and use it in GitHub Desktop.
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 response1 = { | |
| data: { | |
| users: [ | |
| {}, | |
| { | |
| name: 'Oliver', | |
| surname: 'Max', | |
| }, | |
| ], | |
| }, | |
| }; | |
| const response2 = [ | |
| { | |
| data: { | |
| users: [ | |
| {}, | |
| { | |
| name: 'Oliver', | |
| surname: 'Max', | |
| }, | |
| ], | |
| }, | |
| }, | |
| ]; | |
| const get = (data, path, defaultValue = undefined) => path | |
| ?.split(/\.|\[|\]|'|"/) | |
| .filter(Boolean) | |
| .reduce( | |
| (acc, key) => (acc = acc?.hasOwnProperty(key) | |
| ? acc[key] | |
| : defaultValue), | |
| data, | |
| ); | |
| console.log(get(response1, 'data.users[1].name', null)); | |
| console.log(get(response2, '[0]["data"].users[1].surname', null)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment