Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to list in special format in Javascript

I have a string containing comma separated names and optional values that seprated values like this:

var str = "PowerOn:On,ValidLocation, temp:25";

I want to convert it into objects or json that can access to values by name like this:

var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.PowerOn;
alert(result);

OR

var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a["PowerOn"];
alert(result);

Note 1: If a name doesn't have value it be true by default.

Update:

Note 2 :If a name doesn't exist in list the value of it be false: ex:

var a = {"PowerOn":"On", "ValidLocation":"true", "temp":25};
var result = a.Alarm 
//result must be false
like image 506
ArMaN Avatar asked Jul 17 '13 06:07

ArMaN


People also ask

How do you format a string in JavaScript?

JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on.

What is string [] JavaScript?

JavaScript strings are for storing and manipulating text. A JavaScript string is zero or more characters written inside quotes.

How do you turn a string into an array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.

How convert YYYY-MM-DD string to date in JavaScript?

To convert YYYY-MM-DD to MM/DD/YYYY format: Use the split() method to split the string on each hyphen. Add the month , day and year to an array. Join the array elements into a string with a forward slash separator.


1 Answers

var str = "PowerOn:On,ValidLocation, temp:25",
    arr = str.split(','),
    obj = {}

for (var i=0; i<arr.length; i++) {
    var parts = arr[i].split(':');
    obj[parts[0]] = parts[1] || true;
}

JSFIDDLE

like image 193
adeneo Avatar answered Nov 12 '22 04:11

adeneo