-1

I already tried to search thoroughly, but I haven’t found the answer for Javascript.

So: I want to convert to strings (if not already) every JSON value sent to my API from the frontend in order to avoid triggering problems when processing the values.

To do so, I came with three methods:

  • Use String(),
  • Use variable + "",

The two ones above produce the same result.

  • Use .toString() This one is supposed to work as the ones above, converting any number, boolean, undefined or null into a string, but it is failing with null and undefined.

    let data = {
      key1: 1,
      key2: "2",
      key3: false,
      key4: null,
      key5: undefined,
      key6: {
        subkey1: true
      }
    };
    
    console.log("\nString() method:")
    for (let key in data) {
      let stringified = (String(data[key]))
      console.log(stringified)
      console.log(typeof(stringified))
    }
    
    console.log("\nQuotes method:")
    for (let key in data) {
      let quotedValue = (data[key] + "");
      console.log(quotedValue);
      console.log(typeof(quotedValue));
    }
    
    console.log("\ntoString method:")
    for (let key in data) {
      let toStringTest = (data[key].toString());
      console.log(toStringTest);
      console.log(typeof(toStringTest));
    }
    

Which returns:

String() method:
1
string
2
string
false
string
null
string
undefined
string
[object Object]
string

Quotes method:
1
string
2
string
false
string
null
string
undefined
string
[object Object]
string

toString method:
1
string
2
string
false
string
Error:     let toStringTest = (data[key].toString());
TypeError: Cannot read property 'toString' of null

While researching I believe I understood that toString() actually tries to “resolve” the value as if it was an expression or function. Is this accurate?

UserJ
  • 159
  • 3
  • 13
  • You might also get different results when trying it on arbitrary objects. – Bergi Mar 25 '18 at 17:05
  • seems like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) .. what is the expected result? – Slai Mar 25 '18 at 17:14
  • Does this answer your question? [What's the difference between String(value) vs value.toString()](https://stackoverflow.com/questions/3945202/whats-the-difference-between-stringvalue-vs-value-tostring) – frederj Dec 26 '19 at 19:57

2 Answers2

2

.toString() is a method of Object.prototype - you can call it on virtually any JavaScript object. undefined means "doesn't exist", so an attempt to call a method on something that isn't an object will always fail as will calling .toString() on null.

var x;          // Declared but not initialized to anything === undefined
x.toString();   // Cannot read property "toString" of undefined.

var y = null;   // Declared and intentionally set to a value that means no value
y.toString();   // Cannot read property "toString" of null.

But, I think your issue has less to do with strings and more to do with your understanding of undefined and null.

undefined is what you get back when you attempt to get the value of something that doesn't exist. undefined is not meant to be set as the value for something.

Since undefined === doesn't exist, you can't convert doesn't exist to a string. You can query to see if something === undefined or if typeof something === "undefined" and then create an empty string to replace it.

var x;             // undefined
var y = null;

// Check to see if we have something (truthy) or nothing (falsy)
// !! converts a non-Boolean to a Boolean that is opposite of what
// it would normally be. !! converts it back to Boolean equivelent.
console.log(!!x, !!y);

function testForNothing(val){
  // Within an if condition, all values are converted to Booleans by default
  // and implicitly tested for true. We want to test for false (to see if x is
  // NOT something), so a single ! will do the trick
  if(!val){
    console.log(val + " is null or undefined");
  }
}

testForNothing(x);
testForNothing(y);

null is for setting a value that represents nothing.

So, your object is not really correct, it should be:

let data = {
  key1: 1,
  key2: "2",
  key3: false,
  key4: null,
  key5: null,  // <-- null, not undefined!
  key6: {
    subkey1: true
  }
};

Finally, why not use JSON.stringify(), which is designed specifically for this?

let data = {
  key1: 1,
  key2: "2",
  key3: false,
  key4: null,
  key5: null,
  key6: {
    subkey1: true
  }
};

let dataString = JSON.stringify(data);

console.log(typeof dataString, dataString);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

JSON.parse and JSON.stringify exclude only undefined values, but those can be replaced easily:

var data = { key1: 1, key2: "2", key3: false, key4: null, 
             key5: undefined, key6: { subkey1: true } }

console.log( JSON.stringify( data, (k, v) => v === void 0 ? null : v, 2 ) )
Slai
  • 22,144
  • 5
  • 45
  • 53