Problem

Apply a JavaScript function to a property within a JSON document. The property may appear zero or more times at unknown (or unspecified) locations in the document.

Solution

Applies to MarkLogic versions 8+

function applyToProperty(obj, keys, f) {
  for (var i in obj) {
    if (!obj.hasOwnProperty(i)) {
      continue;
    }
    else if (keys.indexOf(i) !== -1) {
      if (Array.isArray(obj[i])) {
        obj[i].forEach(function(item, index){
          obj[i][index] = f.call(this, item);
        });
      } else {
        obj[i] = f.call(this, obj[i]);
      }
    }
    else if (typeof obj[i] === 'object') {
      applyToProperty(obj[i], keys, f);
    }
  }
}

As an example of using this function, let’s add one to the values of JSON properties ‘a’ and ‘b’.

function addOne(n) {
  return n+1;
}

var doc = {
  foo: {
    a: 1,
    b: 2
  },
  blah: [1, 2],
  bar: {
    stuff: {
      a: 1,
      c: 2
    }
  }
};

applyToProperty(doc, ['a', 'b'], addOne);

doc

Discussion

This approach walks through the entire JSON document (actually, a JavaScript object). When it gets to a property that matches one of its targets, it updates the value with the result of calling the provided function on that value. Since this function does recurse through the full input, if you know exactly where changes need to be made, it’s better to simply make that change directly. In other words, if you know that you want to call addOne on doc.foo.a, then call doc.foo.a = addOne(doc.foo.a); rather than calling applyToProperty.

Notice that the document is modified, rather than creating a copy. That means we need to pass in a mutable JavaScript object, not a node.

In lines 3-5, we call hasOwnProperty. The intent is to only pay attention to the data members of the JavaScript object, ignoring any attached functions or properties inherited from the object’s prototype. See hasOwnProperty for more information.

Learn More

Application Developer's Guide

Read the methodologies, concepts, and use cases related to application development in MarkLogic Server, with additional resources.

MarkLogic Developer Learning Track

Want to build that awesome app? Get off the ground quickly with the developer track, with instructor-led and self-paced courses.

Getting Started Video Tutorials for Developers

This series of short videos tutorials takes developers who are new to MarkLogic from download to data hub, fast.

This website uses cookies.

By continuing to use this website you are giving consent to cookies being used in accordance with the MarkLogic Privacy Statement.