Last active
May 27, 2020 19:45
-
-
Save leonidkuznetsov18/a9fa9c804f0a350a695ad5a55274953c to your computer and use it in GitHub Desktop.
Find property by key in deep object
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
// 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; | |
} |
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
Needs explicit
null
check on lines 6 and 30. Also on line 37.