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.

share|improve this question
3  
As there is no such thing as a "Json object", it's hard to get what you want. Maybe you should look at what is JSON ? – dystroy Mar 27 at 8:11
You can match entered text by just doing str.indexOf(search) != -1 – adeneo Mar 27 at 8:22

3 Answers

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.

share|improve this answer

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
}
share|improve this answer
thank you guys. You really save my click. Your solutions are working for me. thank you again. – user1621860 Mar 27 at 9:24
Dude. for (var i = tokens.length; i--;), really? Even while is more readable. – Florian Margaine Mar 27 at 9:29
Well. It saved a click. You can't argue against that. – dystroy Mar 27 at 9:30

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.