7

I have the following string

":All;true:Yes;false:&nbsp"

I want to convert is to an object like:

var listItems = 
[
{itemValue: "", itemText: "All"},
{itemValue: true, itemText: "Yes"},
{itemValue: false, itemText: "&nbsp"}
];

Any elegant way to doing this appreciated.

4 Answers 4

12

With true/false boolean support:

var listItems = [];
var yourString = ":All;true:Yes;false:&nbsp";

var arr = yourString.split(";");
for (var i = 0; i < arr.length; i++) {
    var arr2 = arr[i].split(":");
    var value = arr2[0] || "";
    if (value == "true" || value == "false")
        value = (value === "true");
    listItems.push({
        itemValue : value,
        itemText : arr2[1] || ""
    });
}

console.log(listItems);

DEMO: http://jsfiddle.net/MZKFU/1/


UPDATE. For universal value parsing you can use JSON.parse method with try/catch block, as presented in Esailija's answer.

DEMO: http://jsfiddle.net/MZKFU/2/

Sign up to request clarification or add additional context in comments.

4 Comments

You might want to make that var arr2 = arr[i].split(":",1) which will allow the values to include colons.
Great, but we'd also have to handle "true" and "false": We don't want them to turn up as strings in the resulting JSON, but as booleans.
@GarethMcCaughan It will work only if we have value on the right side :)
@JohannesFahrenkrug Yep, I also have thought about that. Now it supports boolean.
6
var str = ":All;true:Yes;false:&nbsp";
var listItems = str.split(/[;:]/g).map( function(v, i, arr){
    var itemValue;
    if( i % 2 ) {
        return;
    }

    try {
        itemValue = JSON.parse(v);
    }
    catch(e) {
        itemValue = v;
    }

    return {
        itemValue: itemValue,
        itemText: arr[i + 1]
    };
}).filter( Boolean );

Result:

[
Object
itemText: "All"
itemValue: ""
__proto__: Object
, 
Object
itemText: "Yes"
itemValue: true
__proto__: Object
, 
Object
itemText: "&nbsp"
itemValue: false
__proto__: Object
]

8 Comments

Best solution. its a shame 'map' isn't used more in javascript. Its been support in all the major browsers for a while now
Really clever solution! However it fails if you have any string or number as a value. But it can be easily handled.
@VisioN should handle it now. Though not strings (other than empty)
I also tried to use JSON.parse here but it raises exception on any random symbol in the string.
@Vision yes, currently the string needs to be a legit javascript literal (regexp, number, object, array, boolean, null, empty string, etc) or it fails
|
2
var string = ":All;true:Yes;false:&nbsp";
var array = string.split(/:|;/);

var listItems = [];

for (var i = 0; i < array.length; i += 2 ) {
    listItems.push({itemValue: array[i], itemText: array[i + 1]})
}

Notice that this will set "false" and "true" as string. Same for numbers if you have it. If you want save them with the proper types, you have to add a manual conversion. Something like:

function value(val) {
    if (!isNaN(val))
        return +val;

    if (val === "true")
        return true;

    if (val === "false")
        return false;

    return val;
}

Therefore the line that push the object to the array will change as below:

    listItems.push({itemValue: value(array[i]), itemText: array[i + 1]})

Comments

1
var myString = ":All;true:Yes;false:&nbsp"; 
var myArray = myString.split(';');
var literal = [];
for(var i = 0; i<myArray.length; i++){
  var mixed_string = myArray[i];
  var changed_array = mixed_string.split(":");
  var key = changed_array[0];
  var value = changed_array[1];
  literal.push({key:value});
}
console.log(literal);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.