0

In Javascript, is it possible to preserve data type of each data field after splitting it using split method?

Input:

var row = "128, 'FirstName, LastName', null, true, false, null, 'CityName'";

On splitting using split method, the data type of each field is lost. The result is an array of strings as given below.

row.split(',');

["128", " 'FirstName", " LastName'", " null", " true", " false", " null", " 'CityName'"]

A robust CSV to Array function like the one I found here: CSVtoArray also returned the same array of strings output.

Any suggestions?

Community
  • 1
  • 1
Vijey
  • 6,536
  • 7
  • 43
  • 50
  • Why would you want to do so? The `==` operator auto type casts the operands. – AdityaParab Jul 14 '14 at 06:49
  • 1
    You can't "preserve" what isn't there. That's a string. All its substrings are also strings. There's nothing to preserve. If you want to convert parts of it to some other type, you need to impose that type on the parsed substring. – user229044 Jul 14 '14 at 06:52
  • Where is the data coming from? You should fix the problem there. Send the data as JSON for example. – elclanrs Jul 14 '14 at 06:53

1 Answers1

0

We have to explicitly convert from string to the appropriate format. The below given function does that.

  function toNative(value) {
  if (typeof value === 'string') {
    if (value === 'true' || value === 'false') {
      return value === 'true'
    } else if (!isNaN(+value)) {
      return +value
    }
  }
  return value
}

I found this function at: https://github.com/typicode/json-server/blob/master/src/utils.js

Vijey
  • 6,536
  • 7
  • 43
  • 50