Skip to content

Commit

Permalink
add new functionality
Browse files Browse the repository at this point in the history
1) Enable dynamic keys by evaluating any key starting with "$."
2) Enable arrays to be merged to one object
  • Loading branch information
willyboy authored Feb 12, 2018
1 parent e33f4f1 commit dbb8e63
Showing 1 changed file with 28 additions and 12 deletions.
40 changes: 28 additions & 12 deletions lib/jsonpath-object-transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@
*/
function walk(data, path, result, key) {
var fn;

// if the key starts with $., assume that it's dynamic and should be evaluated
if (key && key.toString().indexOf('$.')>-1) {
key = jsonPath.eval(data, key);
}

switch (type(path)) {
case 'string':
fn = seekSingle;
Expand Down Expand Up @@ -72,13 +76,9 @@
* @param {string} key
*/
function seekSingle(data, pathStr, result, key) {
if(pathStr.indexOf('$') < 0){
result[key] = pathStr;
}else{
var seek = jsonPath.eval(data, pathStr) || [];
var seek = jsonPath.eval(data, pathStr) || [];

result[key] = seek.length ? seek[0] : undefined;
}
result[key] = seek.length ? seek[0] : undefined;
}

/**
Expand All @@ -95,11 +95,16 @@
var seek = jsonPath.eval(data, path) || [];

if (seek.length && subpath) {
result = result[key] = [];

result[key] = [];
seek[0].forEach(function(item, index) {
walk(item, subpath, result, index);
walk(item, subpath, result[key], index);
});
if(pathArr[2] && pathArr[2].merge) {
// merge the individual objects in the array into one big object if the merge option is set to true
result[key] = result[key].reduce((reduced, el) => {
return Object.assign(reduced, el);
}, {});
}
} else {
result[key] = seek;
}
Expand Down Expand Up @@ -130,10 +135,21 @@
* @returns {object}
*/
return function(data, path) {
var result = {};

var result = {},
needsWrapper = Array.isArray(data) && Array.isArray(path);
// wrap the data and path in a temp variable that will serve as the key for our initial iteration
// this is to resolve the fact that the code doesn't handle root level arrays natively
if (needsWrapper) {
data = { temp: data };
path = { temp: path };
}

walk(data, path, result);

// unwrap the data before returning it
if (needsWrapper) {
result = result.temp;
}
return result;
};

Expand Down

0 comments on commit dbb8e63

Please sign in to comment.