admin管理员组

文章数量:1417653

I have a JavaScript variable with ma 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.

I have a JavaScript variable with ma 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 edited Mar 27, 2013 at 8:15 Simon Adcock 3,5623 gold badges28 silver badges42 bronze badges asked Mar 27, 2013 at 8:11 user1621860user1621860 412 silver badges8 bronze badges 2
  • 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 ? – Denys Séguret Commented Mar 27, 2013 at 8:11
  • You can match entered text by just doing str.indexOf(search) != -1 – adeneo Commented Mar 27, 2013 at 8:22
Add a ment  | 

4 Answers 4

Reset to default 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
}

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 municate with other languages or pass some data along, there is no need for JSON when you are processing with JavaScript on a single page.

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!!

JSON format requires (single or multi-dimensional) list of key, value pairs. You cannot just convert a ma 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.

本文标签: Convert Javascript string or array into JSON objectStack Overflow