0

I have JSON like below which has every element with field _value

"batchControlInfo" : {
  "sender" : {
    "_value" : "MMRPT"
  },
  "recipient" : {
    "_value" : "AAZTE"
  },
  "fileSequenceNumber" : {
    "_value" : 30
  },
  "fileCreationTimeStamp" : {
    "localTimeStamp" : {
      "_value" : 20200904052019
    },
    "utcTimeOffset" : {
      "_value" : "+0630"
    }
  }
}

How to Convert it to like below, just to remove _value which is in common to every node element.

"batchControlInfo" : {
      "sender" : "MMRPT",
      "recipient""AAZTE",
      "fileSequenceNumber" : 30,
      "fileCreationTimeStamp" : {
        "localTimeStamp" :  20200904052019,
        "utcTimeOffset" : "+0630"
      }
    }

1 Answer 1

3

This can be done recursively as follows.

const input = {
  "batchControlInfo" : {
    "sender" : {
      "_value" : "MMRPT"
    },
    "recipient" : {
      "_value" : "AAZTE"
    },
    "fileSequenceNumber" : {
      "_value" : 30
    },
    "fileCreationTimeStamp" : {
      "localTimeStamp" : {
        "_value" : 20200904052019
      },
      "utcTimeOffset" : {
        "_value" : "+0630"
      }
    }
  }
};

function getResult(input) {
  const output = {};
  for (const key in input) {
    if (input[key] && typeof input[key] === "object") {
      if ("_value" in input[key]) {
        output[key] = input[key]["_value"];
      } else {
        output[key] = getResult(input[key]);
      }
    }
  }
  return output;
}

console.log(getResult(input));

Sign up to request clarification or add additional context in comments.

1 Comment

This will fail when there are objects with values of different type then object that are not named _value. Al tough it works for OP case.You might want to fix that for future readers. Adding else { output[key] = input[key]; } to your first if will fix that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.