Find value of key recursively with JavaScript
01 Dec 2020 in TIL
Here’s a snippet that will allow you to find the values in the key demo no matter where in an object it’s stored. It recursively searches, and includes objects embedded in lists
You’ll need to
npm install object-scan --savefirst
jsconst objectScan = require("object-scan");const findValueByKey = (data, targetKey) => {return objectScan(["**"], {rtn: "value",filterFn: ({ property }) => property == targetKey,})(data);};const data = {demo: "value-one",nested: {demo: "value-two",},listed: [{ demo: "value-three" }],};console.log(findValueByKey(data, "demo"));
This will output the following values:
json["value-three", "value-two", "value-one"]