Open kazurayam opened 4 months ago
I read the source of json-transforms@1.1.2
. I have found out a fix for this issue.
I changed the src/transform.js
.
origin: https://github.com/ColinEberhardt/json-transforms/blob/v1.1.2/src/transform.js
My proposal:
const transform = (json, rules) => {
const runner = match => {
for (let i = 0; i < rules.length; i++) {
const rule = rules[i];
const res = rule(match, adaptedRunner);
if (res !== null) {
return res;
}
}
// at this point, not yet returned.
// the runner function will return "undefined".
};
const adaptedRunner = ast => {
if (Array.isArray(ast)) {
let result = ast.map(r => runner(r));
// a call to runner(r) may return "undefined".
// "undefined" should not appear in the result array.
// so let's filter it out.
result = result.filter((e) => {
return e !== undefined;
});
return result;
} else {
return runner(ast);
}
};
return adaptedRunner(json);
};
export default transform;
I inserted some lines of comments where I explained my idea: what caused "undefined" to be present in the resulting array, how to remove "undefined" away.
With this change to transform.js
applied, the test/topLevelArrayCaseSpec.js
passed. The problem has been fixed.
I am going to create a Pull Request shortly.
I forked this repository, and createded a jasmine test:
test/topLevelArrayCaseSpec.js
When I ran this test, I saw the following result in the console.
Let me explain this case again in another wording.
I have a JSON as input:
Please note that the
automobiles
has, at the top level, an array of objects. This is the point that causesjson-transforms@1.1.2
behave wrongly.I wrote a pathRule as this:
I intended to select the Honda cars while stripping other makers off.
I expected to get the following result:
But in fact,
json-transforms@1.1.2
generated the following result:I think that undefined should NOT be present in the result array.