Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I replace any instance of "" with null in an array of JSON strings in typescript?

I have an array of JSON that looks like this:

[
{"test":"a","test1":"1","test2":""},
{"test":"b","test1":"","test2":"hi"}
{"test":"","test1":"3","test2":""}
]

I want it to look like this if there are any JSON strings with "" values

[
{"test":"a","test1":"1","test2":null},
{"test":"b","test1":null,"test2":"hi"}
{"test":null,"test1":"3","test2":null}
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Loop through the array, then loop through all the properties in each object. Test if the value is an empty string, if so replace it with null.

const data = [
  {"test":"a","test1":"1","test2":""},
  {"test":"b","test1":"","test2":"hi"},
  {"test":"","test1":"3","test2":""}
];

data.forEach(obj => {
  Object.keys(obj).forEach(key => {
    if (obj[key] === "") {
      obj[key] = null;
    }
  });
});

console.log(data);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading