1

I have a JavaScript variable with comma separated string values - i.e. value1,value2,value3, ......,valueX,

I need to convert this variable's values into a JSON object. I will then use this object to match user enteredText value by using filterObj.hasOwnProperty(search)

Please help me to sort this out.

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
user1621860
  • 41
  • 2
  • 8

4 Answers4

3

What you seem to want is to build, from your string, a JavaScript object that would act as a map so that you can efficiently test what values are inside.

You can do it like this :

var str = 'value1,value2,value3,valueX';
var map = {};
var tokens = str.split(',');
for (var i=tokens.length; i--;) map[tokens[i]]=true;

Then you can test if a value is present like this :

if (map[someWord]) {
    // yes it's present
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

Why JSON? You can convert it into an array with split(",").

var csv = 'value1,value2,value3';
var array = csv.split(",");
console.log(array); // ["value1", "value2", "value3"]

Accessing it with array[i] should do the job.

for (var i = 0; i < array.length; i++) {
    // do anything you want with array[i]
}

JSON is used for data interchanging. Unless you would like to communicate with other languages or pass some data along, there is no need for JSON when you are processing with JavaScript on a single page.

Community
  • 1
  • 1
Antony
  • 14,900
  • 10
  • 46
  • 74
0

JavaScript has JSON.stringify() method to convert an object into JSON string and similarly JSON.parse() to convert it back. Read more about it

All about JSON : Why & How

Cheers!!

Cheezy Code
  • 1,685
  • 1
  • 14
  • 18
-1

JSON format requires (single or multi-dimensional) list of key, value pairs. You cannot just convert a comma separated list in to JSON format. You need keys to assign.

Example,

[
  {"key":"value1"},
  {"key":"value2"},
  {"key":"value3"},
  ...
  {"key":"valueX"}
]

I think for your requirement, you can use Array.

Firnas
  • 1,665
  • 4
  • 21
  • 31