transforming json data using recursion

zilcuanu

I have a json data which I need to transform using javascript. The json result is obtained from the server when a user search with keyword. Some objects will be empty and some will contain the data in the search result json. I need to transform into another json which should contain only the objects which has totalRecords attribute value more than 0.

I am adding the link to jsfiddle for the json to be transformed. http://jsfiddle.net/Xhhn4/3/

I tried using recursion to solve the problem. The code for which is below:

  var resultData=data.results;
      var contents = [];
      var get_content=function(resultdata){
        console.log(resultdata);
        $.each(resultdata, function( index, value ) {
          value=value || {};
          if (value.hasOwnProperty("content") && value.content.length > 0 ) {
            contents.push({name:index,value:value});
          }else{
              get_content(value);

          }
        });
      }

      get_content(resultData);
      console.log("Printing the content");
      console.log(contents);

But the above code will give me an array of objects which has content and does not give me the entire tree structure from its root. I Basically need the entire json in the same format with just the empty object removed. Can we achieve this using recursion and how to consolidate the results after the divide with divide and conquer method?

Json Before:

{
  "keywords": [
    "keyword1"
  ],
  "results": {
    "country": {
      "general_search_results": {
        "hospitalDetails": {
          "totalRecords": 0,
          "content": []
        },
        "schoolsDetails": {
          "totalRecords": 0,
          "content": []
        },
        "shoppingMartDetails": {
          "totalRecords": 0,
          "content": []
        }
      },
      "companies_search_results": {
        "totalRecords": 5,
        "content": [
          {
            "companyName": "AAA",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "BBB",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "CCC",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "DDD",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "EEE",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          }
        ]
      },
      "vehicles_search_results": {
        "twoWheelers": {
          "totalRecords": 0,
          "content": [],
        }
      },
      "accidents_search_results": {
        "totalRecords": 0,
        "content": [],
      }
    },
    "state1": {
      "general_search_results": {
        "hospitalDetails": {
          "totalRecords": 0,
          "content": []
        },
        "schoolsDetails": {
          "totalRecords": 0,
          "content": []
        },
        "shoppingMartDetails": {
          "totalRecords": 0,
          "content": []
        }
      },
      "companies_search_results": {
        "totalRecords": 5,
        "content": [
          {
            "companyName": "AAA",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "BBB",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "CCC",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "DDD",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "EEE",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          }
        ]
      },
      "vehicles_search_results": {
        "twoWheelers": {
          "totalRecords": 0,
          "content": [],
        }
      },
      "accidents_search_results": {
        "totalRecords": 0,
        "content": [],
      }
    }
  }
}

Json After format:

{
  "keywords": [
    "keyword1"
  ],
  "results": {
    "country": {
      "companies_search_results": {
        "totalRecords": 5,
        "content": [
          {
            "companyName": "AAA",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "BBB",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "CCC",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "DDD",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "EEE",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          }
        ]
      }
    },
    "state1": {
        "companies_search_results": {
        "totalRecords": 5,
        "content": [
          {
            "companyName": "AAA",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "BBB",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "CCC",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "DDD",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "EEE",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          }
        ]
      }
    }
  }
}
Chris Vouga

This should do the trick

I called the function "prune" because the definition of prune means to trim a tree so it seemed fitting.

const isObject = (o) =>
  typeof o == 'object' && o.constructor == Object;

const isEmptyObject = (o) =>
  Object.entries(o).length === 0

const hasProperty = (key, o) =>
  o.hasOwnProperty(key)

const isPositive = (x) =>
  x > 0

const isEmptyArray = (arr) =>
  arr.length === 0

const pruneReducer = (obj, [key, value]) => {
  if(isObject(value)) {
    if(hasProperty("content", value)) {
      if(isEmptyArray(value.content)) {
        return obj
      } else {
        obj[key] = value
        return obj
      }
    } else {
      const childObj = prune(value)
      if(isEmptyObject(childObj)) {
        return obj
      } else {
        obj[key] = childObj
        return obj
      }
    }
  } else {
    obj[key] = value
    return obj
  }
}

const prune = (obj) =>
  Object.entries(obj).reduce(pruneReducer, {})


const data = {
  "keywords": [
    "keyword1"
  ],
  "results": {
    "country": {
      "general_search_results": {
        "hospitalDetails": {
          "totalRecords": 0,
          "content": []
        },
        "schoolsDetails": {
          "totalRecords": 0,
          "content": []
        },
        "shoppingMartDetails": {
          "totalRecords": 0,
          "content": []
        }
      },
      "companies_search_results": {
        "totalRecords": 5,
        "content": [
          {
            "companyName": "AAA",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "BBB",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "CCC",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "DDD",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "EEE",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          }
        ]
      },
      "vehicles_search_results": {
        "twoWheelers": {
          "totalRecords": 0,
          "content": [],
        }
      },
      "accidents_search_results": {
        "totalRecords": 0,
        "content": [],
      }
    },
    "state1": {
      "general_search_results": {
        "hospitalDetails": {
          "totalRecords": 0,
          "content": []
        },
        "schoolsDetails": {
          "totalRecords": 0,
          "content": []
        },
        "shoppingMartDetails": {
          "totalRecords": 0,
          "content": []
        }
      },
      "companies_search_results": {
        "totalRecords": 5,
        "content": [
          {
            "companyName": "AAA",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "BBB",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "CCC",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "DDD",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          },
          {
            "companyName": "EEE",
            "location": "bangalore",
            "employees": "2000",
            "reputation": 4,
          }
        ]
      },
      "vehicles_search_results": {
        "twoWheelers": {
          "totalRecords": 0,
          "content": [],
        }
      },
      "accidents_search_results": {
        "totalRecords": 0,
        "content": [],
      }
    }
  }
}

console.log(prune(data))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

transforming json data using recursion

From Dev

Transforming a string using just recursion and the concatenation operator

From Dev

Transforming a string using just recursion and the concatenation operator

From Dev

transforming data using sed commands

From Dev

Transforming JSON data to match new Java model

From Dev

transforming JSON data returned from AJAX request

From Dev

Transforming a JSON Object using Dataweave 2.0

From Dev

Transforming nested xml data using xslt

From Dev

Transforming pandas data frame using stack function

From Dev

Recursion using JSON

From Dev

Transforming data

From Dev

How can I apply differnt styles when transforming data using json2html based on data value?

From Dev

Javascript Recursion normalize JSON data

From Dev

What is counterpart of XSLT (transforming XML to HTML) for JSON data files?

From Dev

Return empty array when transforming xml data to json

From Dev

Transforming JSON body using WSO2 class mediator

From Dev

Transforming a tree back to JSON using tree-model-js

From Dev

data.table: Using with=False and transforming function/summary function?

From Dev

Should the action or store be responsible for transforming data when using React + Flux?

From Dev

Should the action or store be responsible for transforming data when using React + Flux?

From Dev

Conditionally transforming a Json

From Dev

Transforming JSON with state in circe

From Dev

Transforming array into json with PHP

From Dev

Conditionally transforming a Json

From Dev

Transforming data for kmeans and PCA

From Dev

Transforming a simple data frame

From Dev

Transforming Data into a timeline

From Dev

Transforming collection using lodash

From Dev

Using recursion to create a JSON string (replicate stringify)

Related Related

  1. 1

    transforming json data using recursion

  2. 2

    Transforming a string using just recursion and the concatenation operator

  3. 3

    Transforming a string using just recursion and the concatenation operator

  4. 4

    transforming data using sed commands

  5. 5

    Transforming JSON data to match new Java model

  6. 6

    transforming JSON data returned from AJAX request

  7. 7

    Transforming a JSON Object using Dataweave 2.0

  8. 8

    Transforming nested xml data using xslt

  9. 9

    Transforming pandas data frame using stack function

  10. 10

    Recursion using JSON

  11. 11

    Transforming data

  12. 12

    How can I apply differnt styles when transforming data using json2html based on data value?

  13. 13

    Javascript Recursion normalize JSON data

  14. 14

    What is counterpart of XSLT (transforming XML to HTML) for JSON data files?

  15. 15

    Return empty array when transforming xml data to json

  16. 16

    Transforming JSON body using WSO2 class mediator

  17. 17

    Transforming a tree back to JSON using tree-model-js

  18. 18

    data.table: Using with=False and transforming function/summary function?

  19. 19

    Should the action or store be responsible for transforming data when using React + Flux?

  20. 20

    Should the action or store be responsible for transforming data when using React + Flux?

  21. 21

    Conditionally transforming a Json

  22. 22

    Transforming JSON with state in circe

  23. 23

    Transforming array into json with PHP

  24. 24

    Conditionally transforming a Json

  25. 25

    Transforming data for kmeans and PCA

  26. 26

    Transforming a simple data frame

  27. 27

    Transforming Data into a timeline

  28. 28

    Transforming collection using lodash

  29. 29

    Using recursion to create a JSON string (replicate stringify)

HotTag

Archive