Recommand · October 22, 2021 0

Convert object to string and fill NA in case value is not present javascript

I am trying to convert a string into an object and fill NA in case the value for that key is not present.

I have a string like this.

 let stroy =  {"Name":"","Id":"abc",  "test": "" "}

with this

JSON.Parse(stroy)

I am able to convert , but How to fill NA in case no value is present.

Is there any other way to do this ?

Thanks

You can loop the object after parsing.
While looping just check whether data found in that key or not

let stroy =  `{"Name":"","Id":"abc",  "test": ""}`
stroy = JSON.parse(stroy)
for (var key in stroy) {
  if(!stroy[key]) {
    stroy[key] = 'NA'
  }
}
console.log(stroy)

You could use Object.keys() and Array.map() to create a list of key / values pairs. If the value is empty we’ll replace it with a default value, in this case ‘NA’.

We’re use Object.fromEntries() to convert back to an object.

let stroy = {"Name":"", "Id":"abc", "test": ""};
const defaultValue = 'NA';

let result = Object.fromEntries(Object.keys(stroy).map(key => {
    return [key, stroy[key] || defaultValue ];
}));

console.log('Result:', result);

You have a extra " in your object it seems.

let stroy =  {"Name":"","Id":"abc",  "test": ""}
let stringStroy = JSON.stringify(stroy).replaceAll('""','"NA"')
console.log(JSON.parse(stringStroy))