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;
}
});
You can make use of the
_.set(object, path, value), it will evaluate the path that you set for each value in your response object.DEMO
Javascript
If you want the
_.eachcallback in a more composed form you can change theevaluate()function like this: