繁体   English   中英

如何将对象的结构转换为另一种结构? JavaScript

[英]How to convert structure of object to another structure? JavaScript

我有这个 JS 对象的结构:

 const obj1 = {
      "groups": [
        {
          "name": "test",
          "type": "app"
        },
        {
          "name": "test2",
          "type": "app"
        },
        {
          "name": "test1",
          "type": "app2"
        },
        {
          "name": "test3",
          "type": "app2"
        }
      ]
    }

我需要最终得到这个: 结果:

 const obj1 = {
      app: {groups: [{name: 'test'},{name: 'test2'}]},
      app2: {groups: [{name: 'test1'},{name: 'test3'}]},
    }

可能是 ES6+ 方法或更旧

这归结为只是通过obj1.groups迭代构建一个新的输出对象:

 const obj1 = { "groups": [ { "name": "test", "type": "app" }, { "name": "test2", "type": "app" }, { "name": "test1", "type": "app2" }, { "name": "test3", "type": "app2" } ] }; const out = {}; for (let group of obj1.groups) { out[group.type] = out[group.type] || { groups: [] }; out[group.type].groups.push({ name: group.name }); } console.log(out);

或者,您可以使用Array.reduce()将其包装成单个表达式:

 const obj1 = { "groups": [ { "name": "test", "type": "app" }, { "name": "test2", "type": "app" }, { "name": "test1", "type": "app2" }, { "name": "test3", "type": "app2" } ] }; const out = obj1.groups.reduce((out, group) => { out[group.type] = out[group.type] || { groups: [] }; out[group.type].groups.push({ name: group.name }); return out; }, {}); console.log(out);

您可以使用Array.reduce()简洁地做到这一点:

 const obj1 = { "groups": [{ "name": "test", "type": "app" }, { "name": "test2", "type": "app" }, { "name": "test1", "type": "app2" }, { "name": "test3", "type": "app2" }] }; const result = obj1.groups.reduce((obj, { name, type }) => { return (obj[type].groups.push({ name }), obj); }, { app: { groups: [] }, app2: { groups: [] } }); console.log(result);

或者使用扩展运算符:

 const obj1 = { "groups": [{ "name": "test", "type": "app" }, { "name": "test2", "type": "app" }, { "name": "test1", "type": "app2" }, { "name": "test3", "type": "app2" }] }; const result = obj1.groups.reduce((o, { name, type }) => ({ ...o, [type]: { groups: [...((o[type] || {}).groups || []), { name }] } }), {}); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM