string to object in javascript

Asked

Viewed 316 times

2

I am receiving an object as a parameter, for example: "4,5", from a function, but I need to exchange the comma for a point. Qnd I do this, the object is changed to string, so I need to return this string to object again. qnd dou u, Alert no typeof(obj), I get a string.

var teste = JSON.stringify(editableObj.innerHTML);
teste = teste.replace(/\,/g, '.');
var obj = JSON.parse(teste);
alert(typeof(obj));
  • 1

    I don’t understand what JSON has to do with this, nor what its real problem is. It can do a [mcve]?

  • i receive an object from a function, then convert it to string using JSON.stringify, to be able to swap the comma for a point, so I need to convert back to object after exchanging the comma for a point.

  • 1

    Just with this I don’t see how I can help you. Maybe this isn’t even the solution. Can you make a [mcve]?

  • Imagine the (Editable.innerHTML), as the q I get from the web form, it comes in object format, and to be clearer the object is a value like: "4,6". so I can update my database, if the value is comma, it doesn’t work. hence I need to exchange the comma for a point. imagine q in the second line of the code, I now have a value= 4.6 and not 4.6 (with comma after user replace it). then this value 4.6 qnd I use Alert (typeof(obg)), I get a string and not an object as I would need to convert from bellows to follow my code and update in the database correctly.

  • Imagining is more complicated, a [mcve] is much easier.

  • unfortunately for you the code is difficult but for me it is well explained, only unsolved.

Show 1 more comment

1 answer

1

The value in editableObj.innerHTML does not return an object, whenever a value of HTML through the innerHTML, the return is always a string. To confirm this type alert(typeof(editableObj.innerHTML)).

editableObj is the object that represents its element, if it is to convert the object to string to make changes your code would be.

var teste = JSON.stringify(editableObj); // passa o Object HTML para string
teste = teste.replace(/\,/g, '.');
var obj = JSON.parse(teste); //Retorna o objeto
alert(typeof(obj));

Now if you just want to replace the , for ., does not need the JSON.

var teste = editableObj.innerHTML.replace(/\,/g, '.');
editableObj.innerHTML = teste;
alert(typeof(teste));

// string
  • ok, you’re right. obg. but debugging through the console, I realized that even though it was an object at the end of the changed code, I realize the value is "Undefined". compared editableObj with obj and returned false.

  • when comparing 2 objects they will always be different, because what is compared is usually the memory address of each one (in most languages).

  • Okay, can you help me once again to solve Undefined? obg.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.