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

Time:09-27

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}
]

CodePudding user response:

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);

CodePudding user response:

You can just iterate over the array and then each key of the objects, checking for a blank string. Like this:

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

for (let entry of data) {
  Object.entries(entry).map(obj => {
    if (obj[1] === "") entry[obj[0]] = null;
  });
}

console.log(data)

CodePudding user response:

you need one line of code

data= JSON.parse( JSON.stringify(data).replaceAll("\"\"","null").replaceAll("\"\"","\""));

CodePudding user response:

This solution is as simple as efficient

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

for(let objData of data)
  for(let propr in objData)
    if(objData[propr] === "")
      objData[propr] = null;
      
console.log(data)

  • Related