Conversion of object properties to numbers

Asked

Viewed 98 times

4

I would like to know how to make the values of an object become numbers. I read about the Methods valueOf(), and toString(), but I have not yet figured out how to use them for this purpose, my attempts have not given much result. I thank you already.

5 answers

2

1

You can use the methods parseInt(<string>) and parseFloat(<string>).

You can see the use of these functions here. But in essence what they do is turn a string into a number, changing the type of string to int (in the case of parseInt) or to floating point (in the case of parseFloat).

1

// Objeto original:
var oSrc = {
  "name": "testy McTestFace",
  "age": "21",
  "canDrink": "1",
  "canDrive": "false"
}

//Conversão de propriedades
for (p in oSrc) {                   // Para cada propriedade,
  oSrc[p] = parseInt(oSrc[p])       // Armazene o valor convertido para inteiro
      || oSrc[p];                   // ou mantenha o valor atual.
} 

console.log(oSrc);

Upshot:

{
  "name": "testy McTestFace",
  "age": 21,                     // Valor convertido
  "canDrink": 1,                 // Valor convertido
  "canDrive": "false"
}

1

Not knowing the context you are trying to use is a bit broad the question, but yes, as mentioned it is possible in some objects to call the methods .valueOf() or .toString() and usefully.

These methods make a conversion from type, object to string or object to number, sometimes "raw" others with semantic sense.

A good example is a Data object, where you can use the .toString() to convert into text, and .valueOf() to convert to a number, the timestamp.

var data = new Date();
data.toString(); // "Fri Jun 03 2016 22:27:57 GMT+0100 (WEST)"
data.valueOf(); // 1464989277351

0

Hello, your question is really kind of without context, but I think I understand what point you want to reach.

The methods .toString() and .valueOf() are special functions that are implicitly called when you use some specific expressions, such as direct conversion to String or Number.

How do you want to know how to use them, so we’ll have to deal with the construction of the object in question.

Example using .toString():


// construtor da "classe" Pessoa
function Pessoa(nome){
    this.nome = nome;

    this.toString = function(){
        return this.nome;
    };
}

var eu = new Pessoa('William');
console.log('Olá, meu nome é '+eu);
// Imprime "Olá, meu nome é William"
console.log(String(eu));
// Imprime "William"

In the case of the method .valueOf(), it explicitly references the value you define, such as your own example, a number:


// construtor de um número "especial"
function NumeroEspecial(num){
    this.num = num;

    this.valueOf = function(){
        return this.num;
    };
}

var num = new NumeroEspecial(5);
console.log(num + 1);
// Imprime 6
console.log(Number(num));
// Imprime 5

This is an explanation only for you know the initial process, there are other factors to consider before using these types of special methods.

Well, I hope I helped!

Browser other questions tagged

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