Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created August 18, 2016 11:00
Show Gist options
  • Save bennadel/8f42a8ac4d7f63fb807c51408a75d1a5 to your computer and use it in GitHub Desktop.
Save bennadel/8f42a8ac4d7f63fb807c51408a75d1a5 to your computer and use it in GitHub Desktop.
Code Kata: Using Array Reduce() To Navigate An Object Graph In JavaScript
// I am just an arbitrarily non-trivial object to query.
var config = {
tasks: {
interval: {
//...
},
daily: {
backupFilesToS3: {
dayOfWeek: "Saturday",
hour: 22
}
}
}
};
// Now, imagine that we are given an object query that is a dot-delimited path of
// object navigation instructions. And, we want to find the value that resides at
// the end of this path.
var objectQuery = "tasks.daily.backupFilesToS3.dayOfWeek";
var value = objectQuery
// To find the value, we can split the query / object-path on the dot-operator and
// treat each token as a single object-property navigation instruction.
.split( "." )
// With the resultant array of navigation tokens, we can then reduce the set of
// steps down to the target value by using the reduction's "previousValue" as our
// place-holder in the object graph. Essentially, each step of the reduce() operation
// takes us one level deeper into the object graph, returning the result of a single
// step in the object path.
.reduce(
function iterator( previousValue, navigationToken ) {
// If the previous navigation was successful, return the result of the NEXT
// step in set of navigation operations. Otherwise, return the failed result
// of the previous navigation.
return( previousValue && previousValue[ navigationToken ] );
},
config // ... starting at the root of the object graph.
)
;
console.log( "Query Result:", value );
// ----------------------------------------------------------------------------------- //
// ----------------------------------------------------------------------------------- //
// And, of course, there's the old-school way to just evaluate the code :D Which is
// likely to throw red-flags by your team's linting system and code-review process.
console.log( "EVAL Query Result:", eval( "config." + objectQuery ) );
@ultraq
Copy link

ultraq commented May 7, 2017

Nice 👍 I was able to get as far as tokens for each of the . parts, but converting that to traversing the object graph was where I got stuck (I was heading towards a for/while loop and the array shift method, but really like elegance of your solution).

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