我有以下 json
{"结果": { "a": 1, "b": 2 "c": [ { "d": 3, "e": 4 }, { "d": 3, "e": 4 } ] }}
我想把它改成这样:
{"结果": [{ "a": 1, "b": 2, "d": 3, "e": 4 }, { "a": 1, "b": 2 ,“d”:3,“e”:4}]}
有没有办法像这样改变JSON?
最佳答案
您可以使用Array.prototype.reduce()
来实现:
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:[]});
或者如果它应该更加动态,那么像这样:
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:[]});
关于javascript - 如何改变JSON格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13281142/