Created
December 18, 2021 01:07
-
-
Save shawn-dsz/acea16fd4ab364be7436b183edc7c1aa to your computer and use it in GitHub Desktop.
recursively find objects by key
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 data = [ | |
| { | |
| title: 'some title', | |
| channel_id: '123we', | |
| options: [ | |
| { | |
| channel_id: 'abc', | |
| image: 'http://asdasd.com/all-inclusive-block-img.jpg', | |
| title: 'All-Inclusive', | |
| options: [ | |
| { | |
| channel_id: 'dsa2', | |
| title: 'Some Recommends', | |
| options: [ | |
| { | |
| image: 'http://www.asdasd.com', | |
| title: 'Sandals', | |
| id: '1', | |
| content: {}, | |
| }, | |
| ], | |
| }, | |
| ], | |
| }, | |
| ], | |
| }, | |
| ]; | |
| Object.entries({a: 1, b: 3}) | |
| function _find(collection, key, value) { | |
| for (const o of collection) { | |
| o | |
| for (const [k, v] of Object.entries(o)) { | |
| if (k === key && v === value) { | |
| return o; | |
| } | |
| if (Array.isArray(v)) { | |
| const _o = _find(v, key, value); | |
| if (_o) { | |
| return _o; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| console.log(_find(data, 'channel_id', 'dsa2')); | |
| function findAllByKey(obj, keyToFind) { | |
| return Object.entries(obj).reduce( | |
| (acc, [key, value]) => | |
| key === keyToFind | |
| ? acc.concat({ key: value }) | |
| : typeof value === 'object' | |
| ? acc.concat(findAllByKey(value, keyToFind)) | |
| : acc, | |
| [] | |
| ); | |
| } | |
| findAllByKey(data, 'channel_id'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment