Skip to main content

Recursively Search and Update a JSON/JavaScript Object

Hello my blog. Sorry I haven't updated you in a while, but I've been busy. However it seems like I have a reason to start writing again, so here we go.

The other day I came across the following problem.

I have a JSON export of a data schema from inRiver, and I have a CSV file with translations for each property in inRiver. The only thing I need to do is to update the JSON export with the values from the CSV file.

Easy! Or not so easy. I quickly figured out that C# was not the language for this task. I would be better off using a dynamic language like javascript.

The gist here is not about reading or parsing CSV or JSON, but rather how to search and update a big javascript object. If it were XML, I would just have used XSLT and be done in a snap.

Let's look at the end result.

// findObjectById: helper function
// comment: will recurse through an object graph, looking for matching Id's and run the update function
const findObjectById = (obj, id, updateFn) => {
  // have found the object
  if (obj["Id"] === id) {
    return updateFn(obj);
  else {
    // iterate over the properties
    for (var propertyName in obj) {
      // any object that is not a simple value
      if (obj[propertyName] !== null && typeof obj[propertyName] === 'object') {
        // recurse into the object and write back the result to the object graph
        obj[propertyName] = findObjectById(obj[propertyName], id, updateFn);
  return obj;

This code will recurse through an object graph, looking for an object with matching ID property. If it finds it, it will run the update function on that object.

The important thing to notice in this code is that javascript is always copy by value. We cannot just recurse down to the part we want to change and update it, because then we would update a copy of the object. Instead we need to make sure that we write back each recursion to the object graph to get the change in the end.

This is how we use it!

var animals = {
    anything {
        ID = '123',
        Name = {
            'en': 'Phoney Pony'

var updateFn = obj => { obj.Name['sv-SE'] = 'Fånig ponny' };

var result = findObjectById(animals, '123', updateFn);

// the result will look like this // var animals = { // anything { // ID = '123', // Name = { // 'en': 'Phoney Pony', // 'sv-SE': 'Fånig ponny' // } // } // };

Happy Coding!

comments powered by Disqus