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

时间:2019-02-18 16:34:49

标签: javascript

我具有JS对象的这种结构:

CREATE TABLE "schema1.myuser"

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

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

可能是ES6 +或更高版本

2 个答案:

答案 0 :(得分:1)

这归结为只是迭代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);

答案 1 :(得分:-1)

您可以使用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);