5

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
1
  • What Can I DO? I recieve a string from a database and i must parse it :(
    – ArMaN
    Jul 17, 2013 at 6:19

2 Answers 2

7
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

6
  • so thanx :) another problem: if a name doesn't exist in list i want the value of it be false: ex: var result = a.Alarm
    – ArMaN
    Jul 17, 2013 at 6:24
  • @ArMaN it won't be false. It'll be undefined, but that's falsy anyways, so if you do if(!obj.NonExistingKey){alert('doesn\'t exist');} you'll get an alert...
    – Alxandr
    Jul 17, 2013 at 6:27
  • 1
    Just do var result = a.Alarm || false, or var result = Alarm in a ? a.Alarm : false; etc
    – adeneo
    Jul 17, 2013 at 6:29
  • 1
    @adeneo Also, this will cause problems if you have an empty string, or space in front of the keys (as shown on the temp one). See updated fiddle: jsfiddle.net/TxMhM/1 can't guarantee this is what OP wants though.
    – Alxandr
    Jul 17, 2013 at 6:32
  • 1
    @Alxandr - Yeah, there are still a lot of things that could go wrong, so trimming and optimizing to make sure the values are valid is always a good idea if the OP isn't sure the original string is exactly like in the question.
    – adeneo
    Jul 17, 2013 at 6:36
1

Assuming the delimiters remain as such, Does this work for you :

var result = {}; 

"PowerOn:On,ValidLocation, temp:25".split(",").forEach(function(i) { 
           result[(i=i.split(":"))[0]]=i[1] || true; 
});

// result : {PowerOn: "On", ValidLocation: true,  temp: "25"}

To the second part of you question use !!result.Alarm which should be false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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