Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapping json object with weird json fields, indexed by number using lodash

I am trying to parse a json response from a server. There is nothing I can do with the server side, as it cannot be changed any time soon.

Here is what their json response looks like:

{
    prop[1][foo]: "foo number 1",
    prop[1][bar]: "bar number 1",
    prop[1][bazz]: "bazz number 1",
    prop[2][foo]: "foo number 2",
    prop[2][bar]: "bar number 2",
    prop[2][bazz]: "bazz number 2"
}

Now I want it to be like this:

{
    props: [
        {foo: "foo number 1", bar: "bar number 1", bazz: "bazz number 1"},
        {foo: "foo number 2", bar: "bar number 2", bazz: "bazz number 2"}
    ]
}

How do I do this, I can't figure out how to iterate and set things over.

My attempt:

var temp = [];

var regExp = /\[([^)])\]/;
var matches;
_.each(element, function(value, key) {
    if (key.indexOf('foo') >= 0) {
        matches = regExp.exec(key);
        temp[matches[1]] = value;
    }

});
like image 252
Joey Hipolito Avatar asked Dec 14 '25 14:12

Joey Hipolito


1 Answers

We can do string manipulation, because using "eval()" is a bad idea in javascript

var injson = '{prop[1][foo]: "foo number 1",    prop[1][bar]: "bar number 1",    prop[1][bazz]: "bazz number 1",    prop[2][foo]: "foo number 2",    prop[2][bar]: "bar number 2",    prop[2][bazz]: "bazz number 2"}'

injson = injson.replace("{","");
injson = injson.replace("}","");
injson = injson.split("\",");

var outarr = [];

for(var index=0;index<injson.length;index++){
    var _key = $.trim(injson[index].split(":")[0]);
    var _value = $.trim(injson[index].split(":")[1]);
    _value = _value.substring(1, _value.length-1);
    var _index = parseInt(_key.substring(_key.indexOf("[")+1).substring(0,1));
    var _prop = _key.substring(_key.indexOf("][")+2, _key.length-1);
    if(!outarr[_index])
       outarr[_index] = {};
    outarr[_index][_prop] = _value;
};
console.log(outarr);

Something like this

In case if you want to use eval you can try to reduce the code inside the for loop

like image 117
Dickens A S Avatar answered Dec 16 '25 06:12

Dickens A S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!