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
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.
JavaScript strings are for storing and manipulating text. A JavaScript string is zero or more characters written inside quotes.
The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With