Home > Enterprise >  Json obj is not acting correct way in javascript
Json obj is not acting correct way in javascript

Time:10-27

I am trying to get form data to json object and modify it... But it is not working...
Here is my code-

let formData = new FormData(thisForm).entries();

let body = JSON.stringify(Object.fromEntries(formData));
console.log(body);
console.log(body.firstName);
console.log("service="   body.service);
body.service = "hello";

the console.log(body) is printing output like this-

{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}

But console.log(body.firstName); is printing undefined.
Same thing is happening for other things.. What is the problem?

CodePudding user response:

It's because body is a string, not a JSON object, because you've JSON.stringify'd it.

Use JSON.parse instead to create a JSON object that you can edit like that.

var body = '{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}';

var jsonBody = JSON.parse(body);
console.log(jsonBody.firstName);

CodePudding user response:

Because you use JSON.stringify() on the object first. You use that to transfer the object over http. Apply that later on and you're fine.

  • Related