Skip to content

Instantly share code, notes, and snippets.

@shawn-dsz
Created December 18, 2021 01:07
Show Gist options
  • Save shawn-dsz/acea16fd4ab364be7436b183edc7c1aa to your computer and use it in GitHub Desktop.
Save shawn-dsz/acea16fd4ab364be7436b183edc7c1aa to your computer and use it in GitHub Desktop.
recursively find objects by key
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