当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - From String to Object

问题描述:

I need to go from

'IsEditOnly=False;IsLastFieldInRow=False;IsReadOnly=False;Title=bedrijfStandaard;Width=100'

to something like

{IsEditOnly: false, Title: 'bedrijfStandaard'}

Thanks

网友答案:
var s='IsEditOnly=False;IsLastFieldInRow=False;IsReadOnly=False;Title=bedrijfStandaard;Width=100';
s=s.replace(/=/g, ':"');
s=s.replace(/;/g, '",');
s+='"';
eval('var obj={'+s+'}');
alert(obj.Width);

http://jsfiddle.net/w1yq4vtc/

网友答案:

You could try this:

var queryToObject = function(s){
    var
    i = 0,
    retObj = {},
    pair = null,
    qArr = s.split(';');

    for (; i < qArr.length; i++){
        pair = qArr[i].split('=');
        retObj[pair[0]] = pair[1];
    };

    return retObj;
};

var query = 'IsEditOnly=False;IsLastFieldInRow=False;IsReadOnly=False;Title=bedrijfStandaard;Width=100';
console.dir(queryToObject(query));

JSFiddle

分享给朋友:
您可能感兴趣的文章:
随机阅读: