Skip to content

Instantly share code, notes, and snippets.

@leonidkuznetsov18
Last active May 27, 2020 19:45
Show Gist options
  • Save leonidkuznetsov18/a9fa9c804f0a350a695ad5a55274953c to your computer and use it in GitHub Desktop.
Save leonidkuznetsov18/a9fa9c804f0a350a695ad5a55274953c to your computer and use it in GitHub Desktop.
Find property by key in deep object
// with recursion
function findAll(obj, key){
if(Array.isArray(obj)){
return obj.reduce((a,v) => a.concat(findAll(v, key)),[]);
}
if(typeof obj === 'object'){
return Object.keys(obj).reduce(function(v, k){
if(k === key){
return v.concat(obj[k]);
}
if(typeof obj[k] === 'object'){
return v.concat(findAll(obj[k], key));
}
return v;
}, [])
}
return [];
}
// without recursion
function findAll(obj, key) {
var result = [];
if (!Array.isArray(obj)) {
obj = [obj];
}
for (var i = 0; i < obj.length; i++) {
if (Array.isArray(obj[i])) {
obj = obj.concat(obj[i]);
} else if (typeof obj[i] === "object") {
Object.keys(obj[i]).forEach(k => {
if (k === key) {
result.push(obj[i][k]);
}
if (Array.isArray(obj[i][k])) {
obj = obj.concat(obj[i][k]);
} else if (typeof obj[i][k] === "object") {
obj.push(obj[i][k]);
}
})
}
}
return result;
}
@stasgavrylov
Copy link

stasgavrylov commented Jul 18, 2018

Needs explicit null check on lines 6 and 30. Also on line 37.

@blackakula
Copy link

Totally the same with walk-composite library:

import {Walk} from 'walk-composite';
const findAll = (obj, key) => {
    let values = [];
    Walk({
        keysMethod: structure => {
            const value = structure[key];
            if (value !== undefined) {
                values.push(value);
            }
            return Object.keys(structure);
        }
    })(() => {})(obj)
    return values;
}

BTW, null checks are built-in the library: data === null || typeof data !== 'object'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment