简体   繁体   中英

convert a string to javascript object

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.

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/

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
]
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]})
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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM