How do I merge a JSON child with it's parent using JavaScript

Viewed 624

I have a JSON like so:

{
  "parent": {
    "type": "Object",
    "value": {
        "childName": { "type": "String", "value": "A string" }
       }
   }
}         

Pretty much, the pattern is parent has type and value, but I want the value of parent to be value

{
  "parent": {
    "childName": "A string"
  }
}

How can I set the parent's value to be the child named value recursively in JavaScript?

The main issue I am having is doing this recursively for a very large file.

Examples:

The start value of Level is `{ "type": "string", "value": "A string" }

I want to make the value of Level become "A String", making the end value of Level become "A String"


The start value of parentObject is { "type": "Object", "value": { "anotherObject": { "type": "string", "value": "Another string" }, "secondObject": { "type": "string", "value": "second string" } } }

I want to make the value of parentObject become { "anotherObject": { "type": "string", "value": "Another string" }, "secondObject": { "type": "string", "value": "second string" } }

And the value of anotherObject become "Another string"

Making the final result

{"parentObject": { "anotherObject": "Another string" }, { "secondObject": "second string" }}

Here is a example JSON file

1 Answers

The first thing is the object should be symmetric if your want to do it in a recursive way.

Example:

const input = {
  "parentObject": {
    "type": "Object",
    "value": {
      "anotherObject": {
        "type": "string",
        "value": "Another string"
      }
    }
  }
};

The recursive function is something like this.

const input = {
  "parentObject": {
    "type": "Object",
    "value": {
      "anotherObject1": {
        "type": "string",
        "value": "Another string"
      },
      "anotherObject2": {
        "type": "string",
        "value": "Another string"
      }
    }
  }
};

const recursivefn = (obj) => {
    const keys = Object.keys(obj);
    let acc = {}
    keys.forEach((key)=>{
      if (typeof obj[key].value === 'object') {
          acc = { ...acc, [key]: recursivefn(obj[key].value) };
      } else {
          acc = { ...acc, [key]: obj[key].value};
      }
    });
    return acc;
}
console.log(recursivefn(input));

Related