0

I have a situation where I have an object with multiple keys like

let obj ={
 a:"33",
  b:"44",

}

There can be many keys with values.Now what I am looking for is to create a method

such that

obj.prototype.toNumber=function()
{
   // change the particular key's value for which its called to number
}

So suppose if I do like obj["a"].toNumber() ; // Will change the value of obj["a"] to the number

or Do I have to add this method on string prototype?

gANDALF
  • 360
  • 4
  • 21
  • 2
    *"Do I have to add this method on string prototype"* If you wanted to call it on a String value then yes. But since String values are immutable, there is no advantage to do that. Neither would it magically update the object property holding the value. You are better off just creating a helper function that you call with `toNumber(obj, 'a')`, or even better, be explicit: `obj['a'] = toNumber(obj['a'])`. – Felix Kling Feb 16 '21 at 13:01
  • Well then I can use a `Number() ` consturctor or `parseInt()` may be – gANDALF Feb 16 '21 at 13:02
  • Yes, you can do `obj['a'] = Number(obj['a'])`. – Felix Kling Feb 16 '21 at 13:02

2 Answers2

2

Do I have to add this method on string prototype?

Your example usage would be trying to use it on a string, so in that sense yes; but it won't work to define the method there, because it has no idea what object the string came from, so it can't write the number value back to the object's property.

Your best bet is just to create a utility function you pass the object and property name to:

function propToNumber(obj, name) {
    obj[name] = +obj[name]; // Or any of several others ways to do the string->number conversion
}

You'd use that like this: propToNumber(obj, "b").

Alternatively you could define a method on the object to do it:

let obj ={
    a:"33",
    b:"44",
    propToNumber(name) {
        this[name] = +this[name];
    },
};

You'd use that like this: obj.propToNumber("b").


Re the part converting from string to number, my answer here goes into details of your various options for doing that.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

You can include the function as part of the object like the following way:

let obj ={
  a:"33",
  b:"44",
  toNumber: function(a){
    this[a] = Number(this[a]);
    console.log(typeof(this[a]));
  }
}

obj.toNumber('a') ;
Mamun
  • 66,969
  • 9
  • 47
  • 59