How to change JSON form?
Problem
I have following json
{"result": { "a": 1, "b": 2 "c": [ { "d": 3, "e": 4 }, { "d": 3, "e": 4 } ] }}
I want to change it become like this:
{"result": [{ "a": 1, "b": 2, "d": 3, "e": 4 }, { "a": 1, "b": 2, "d": 3, "e": 4 }]}
is there a way change JSON like this?
Problem Courtesy of: Claud Kho
Solution
You can use Array.prototype.reduce()
for this:
var obj = {"result": { "a": 1, "b": 2, "c": [ { "d": 3, "e": 4 }, { "d": 3, "e": 4 } ] }};
var res = obj.result.c.reduce(function(res, arrObj) {
res.result.push({a:obj.result.a, b:obj.result.b, d:arrObj.d, e:arrObj.e});
return res;
}, {result:[]});
Or if it should be more dynamic, then like this:
var res = obj.result.c.reduce(function(res, arrObj) {
Object.keys(obj.result).forEach(function(key) {
if (typeof obj.result[key] !== 'object')
arrObj[key] = obj.result[key];
});
res.result.push(arrObj);
return res;
}, {result:[]});
Solution courtesy of: I Hate Lazy
Discussion
View additional discussion.