jqueryarraysjsonkey-valuekey-value-store

Convert comma separate string to Key value object jQuery


I have following string:

var attrs = "FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT"

and want to convert it to key value object like below using jQuery.

attrs = {
        FName:abraham,
        LName:lincoln,
        COUNTRY:USA,
        JOB:PRESIDENT
        }

Solution

  • you can make use of split and create object, see below

    var attrs = "FNAME=abraham,LNAME=lincoln,COUNTRY=USA,JOB=PRESIDENT";
    var values = attrs.split(",");
    var obj = {};
    for(var i=0; i<values.length; i++) {
        var keyValue = values[i].split("=");
        obj[keyValue[0]] = keyValue[1];
    }
    console.log(obj);