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
CodePudding user response:
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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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))