开发者

Transform a string into array using javascript

开发者 https://www.devze.com 2023-03-25 14:16 出处:网络
I have a string like this: string = \"locations[0][street]=street&locations[0][street_no]= 34&locations[1][street]=AnotherStreet&locations[1][street_no]=43\";

I have a string like this:

string = "locations[0][street]=street&locations[0][street_no]=
         34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";

What must I do with this string so i can play w开发者_开发技巧ith locations[][] as I wish?


You could write a parser:

var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";


function parseArray(str) {
    var arr = new Array();
    var tmp = myStr.split('&');
    var lastIdx;
    for (var i = 0; i < tmp.length; i++) {
        var parts = tmp[i].split('=');
        var m = parts[0].match(/\[[\w]+\]/g);
        var idx = m[0].substring(1, m[0].length - 1);
        var key = m[1].substring(1, m[1].length - 1);
        if (lastIdx != idx) {
            lastIdx = idx;
            arr.push({});
        }
        arr[idx * 1][key] = parts[1];
    }
    return arr;
}

var myArr = parseArray(myStr);


As Shadow wizard said, using split and eval seems to be the solution. You need to initialize locations first, if you want to avoid an error.

stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
    eval(stringArray[i]);
}

However, you might need to pay attention to what street and street_no are. As is, it will produce an error because street is not defined.

Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.

0

精彩评论

暂无评论...
验证码 换一张
取 消