如何更改JSON表单?

时间:2012-11-08 01:30:17

标签: javascript json node.js mongodb

我跟随json

{"result": { "a": 1, "b": 2 "c": [ { "d": 3, "e": 4 }, { "d": 3, "e": 4 } ] }}

我想改变它变成这样:

{"result": [{ "a": 1, "b": 2, "d": 3, "e": 4 }, { "a": 1, "b": 2, "d": 3, "e": 4 }]}

有没有办法改变像这样的JSON?

1 个答案:

答案 0 :(得分:3)

您可以使用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:[]});