diff --git a/lib/index.js b/lib/index.js index 8f5a832..c34ce25 100755 --- a/lib/index.js +++ b/lib/index.js @@ -39,8 +39,8 @@ JSONPath.prototype.apply = function(obj, string, fn) { }); nodes.forEach(function(node) { - var key = node.path.pop(); - var parent = this.value(obj, this.stringify(node.path)); + var key = node.path.slice(-1); + var parent = this.value(obj, this.stringify(node.path.slice(0, -1))); var val = node.value = fn.call(obj, parent[key]); parent[key] = val; }, this); diff --git a/test/sugar.js b/test/sugar.js index 98a21b9..b2fd368 100644 --- a/test/sugar.js +++ b/test/sugar.js @@ -1,6 +1,7 @@ var assert = require('assert'); var jp = require('../'); var util = require('util'); +var storeData = require('./data/store.json'); suite('sugar', function() { @@ -25,6 +26,18 @@ suite('sugar', function() { assert.deepEqual(data.a.b, [{c: [3, 2]}, 1]); }); + test('apply method reports matched nodes', function() { + var results = jp.apply(storeData, '$..author', function(value) { + return value.toUpperCase(); + }); + assert.deepEqual(results, [ + { path: ['$', 'store', 'book', 0, 'author'], value: 'NIGEL REES' }, + { path: ['$', 'store', 'book', 1, 'author'], value: 'EVELYN WAUGH' }, + { path: ['$', 'store', 'book', 2, 'author'], value: 'HERMAN MELVILLE' }, + { path: ['$', 'store', 'book', 3, 'author'], value: 'J. R. R. TOLKIEN' } + ]); + }); + test('value method gets us a value', function() { var data = { a: 1, b: 2, c: 3, z: { a: 100, b: 200 } }; var b = jp.value(data, '$..b')