Home > Enterprise >  reformatting json file to have identifying attribute and array to accomodate for sub-objects
reformatting json file to have identifying attribute and array to accomodate for sub-objects

Time:07-10

I am trying to reformat some relatively unstructured json to fit my needs, where I want each object to have a 'name' attribute as well as a 'children' array for sub-objects. I have a json file that looks like below:

{
"varA":true,
"varB":false,
"varC": {
        "time":"15:00:00",
        "date":"Jul 10",
        "items":["apple", banana"]
        }
}

I would like to format it to be something like this:

{
"name": "data",
"children": [
  {
  "name": "varA",
  "children": [
    {"name": "true"}
  ]
  },
  {
  "name": "varB",
  "children": [
    {"name": "false"}
  ]
  },
  {
  "name": "varC",
  "children": [
    {
        "name": "time",
        "children": [
            {"name": "15:00:00"}
        ]
    },
    {
        "name": "date",
        "children": [
            {"name": "Jul 10"}
        ]
    },
    {
        "name": "items",
        "children": [
            {"name": "apple"},
            {"name": "banana"}
        ]
    }
  ]
  }

]
}

How would I be able to do this recursively using pure js, in the case that objects can have a different depths of subobjects? Or is it still possible to do it iteratively?

Thanks in advance!!!

CodePudding user response:

const data = {
    "varA":true,
    "varB":false,
    "varC": {
        "time":"15:00:00",
        "date":"Jul 10",
        "items":["apple", "banana"]
    }
}

function parse(key, val) {
    if (val === undefined) return { name: key };


    if (typeof val !== "object") {
        return {
           name: key,
           children: [
              parse(val)
           ]
        }
    }


    return {
        name: key,
        children: Object.entries(val).map(([newKey, newVal]) => parse(newKey, newVal))
    }
}

const parsedData = parse("data", data)
  • Related