javascript - 如何改变JSON格式?

标签 javascript json node.js mongodb

我有以下 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/

相关文章:

javascript - React-Redux - 切换按钮以显示和隐藏详细信息

jquery - jQuery JSON ajax 请求上的空请求正文

javascript - 防止 NodeJS 在开发/调试时缩小 JavaScript 代码

node.js - 将更新部署到生产 node.js 代码

javascript - 从元素中删除类而不影响正在进行的 css 转换

php - JQuery 读取 Cookie 并将其传递给 PHP 变量?

javascript - react-redux 错误 : Actions must be plain objects. 使用自定义中间件进行异步操作

javascript - Grunt 未加载

arrays - 如何过滤掉 Gerrit JSON api 响应的前几个坏字符

javascript - 使用 Node 和请求模块编写 GET 请求