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