Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix transform function logic for deeply nested jsonb #530

Merged
merged 5 commits into from
Jan 3, 2023

Conversation

Eprince-hub
Copy link
Contributor

The createJsonTransform() function is not transforming deeply nested objects and arrays in jsonb

function createJsonTransform(fn) {
  return function jsonTransform(x, column) {
    return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)
      ? Array.isArray(x)
        ? x.map(x => jsonTransform(x, column))
        : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: v }), {})
      : x
  }
}

Problem

It wasn't transforming deeply nested arrays and objects because the reduce() method only iterate over the keys and values of the top-level object. It does not recursively transform the keys of any subsequent nested objects.

Solution

jsonTransform() function needs to be called on the values of each key-value pair in the object so that it can keep iterating and transforming them regardless of how deeply nested they are.
Example:

function createJsonTransform(fn) {
  return function jsonTransform(x, column) {
    return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802)
      ? Array.isArray(x)
        // Recursively transform array elements
        ? x.map(x => jsonTransform(x, column))
        // Recursively transform object keys and values
        : Object.entries(x).reduce((acc, [k, v]) => {
          // Use fn() to transform the key
          const transformedKey = fn(k);
          return Object.assign(acc, { [transformedKey]: jsonTransform(v, column) });
        }, {})
      // Return non-object values as-is
      : x;
  };
}

@porsager porsager merged commit a848ca6 into porsager:master Jan 3, 2023
porsager pushed a commit that referenced this pull request Feb 1, 2023
* Refactor createJsonTransform logic

* Add tests for deeply nested json

* Remove test for deeply nested json

* Nested object test

* Add Nested array test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants