I have the following string
":All;true:Yes;false: "
I want to convert is to an object like:
var listItems =
[
{itemValue: "", itemText: "All"},
{itemValue: true, itemText: "Yes"},
{itemValue: false, itemText: " "}
];
Any elegant way to doing this appreciated.
With true/false
boolean support:
var listItems = [];
var yourString = ":All;true:Yes;false: ";
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/
var str = ":All;true:Yes;false: ";
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: " "
itemValue: false
__proto__: Object
]
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