首页 > 解决方案 > 使用不可变 javascript/node 的“真实世界”JSON 转换

问题描述

背景

我将使用数组的非平凡 JSON 响应转换为

我使用临时变量、foreach 循环和一些条件逻辑来做到这一点。我的第一个工作代码,示例输入/输出 JSON 如下。

问题/关注

虽然这可行,但我担心代码的“气味”和可维护性。有没有一种更易于维护的方法(也许使用 Array....、map、filter、reduce)?我不是在寻找一个可行的解决方案,而是寻找“一个衬里”。

代码

const raw = require('./tests/data/raw.json');

function parseLoc(loc) {
  const types = new Set();

  // constant properties with loc_id the name of the object
  let o = { [loc.loc_id]: { last_update: loc.last_update, type_id: loc.type_id } };
  types.add(loc.type_id);
  // optional property
  if (loc.contents) {
    o = { [loc.loc_id]: { ...o[loc.loc_id], contents: loc.contents } };
    loc.contents.forEach((item) => {
      types.add(item.type_id); // can have nested types
    });
  }
  // optional property
  if (loc.plan_id) {
    o = { [loc.loc_id]: { ...o[loc.loc_id], plan_id: loc.plan_id } };
  }
  // summary properties
  o = {
    [loc.loc_id]: {
      ...o[loc.loc_id],
      Types: [...types],
    },
  };
  return o;
}

const driver = () => {
  const { locs } = raw[Object.keys(raw)[0]];

  let out = {};
  locs.forEach((loc) => {
    const t = parseLoc(loc);
    out = { ...out, [Object.keys(t)[0]]: t[Object.keys(t)[0]] };
  });
  console.log('out', out);
};

driver();

输入

   {
  "Input": {
    "locs": [
      {
        "contents": [{ "amount": 1, "type_id": 2393 }],
        "last_update": "2013-09-22T21:53:51Z",
        "obsolete1": 1.52384062551,
        "obsolete2": 1.56361060962,
        "loc_id": 1011160470678,
        "type_id": 2524
      },
      {
        "last_update": "2019-07-29T10:56:27Z",
        "obsolete1": 1.60921860432,
        "obsolete2": 1.60545414964,
        "loc_id": 1028580652821,
        "plan_id": 97,
        "type_id": 2474
      },
      {
        "contents": [
          { "amount": 560, "type_id": 2393 },
          { "amount": 560, "type_id": 9838 },
          { "amount": 560, "type_id": 2317 },
        ],
        "last_update": "2019-02-28T22:09:51Z",
        "obsolete1": 1.55924075537,
        "obsolete2": 1.58171860958,
        "loc_id": 1029669382563,
        "type_id": 2544
      }
    ]
  }
}

输出

{
  "Output": {
    "types": [2393, 9838, 2524, 2474, 2312],
    "locs": {
      "1011160470678": {
        "last_update": "2013-09-22T21:53:51Z",
        "type_id": 2524
      },
      "1028580652821": {
        "contents": [{ "amount": 560, "type_id": 9838 }],
        "last_update": "2019-07-29T10:56:27Z",
        "plan_id": 97,
        "type_id": 2474
      },
      "1029669382563": {
        "contents": [
          { "amount": 560, "type_id": 2393 },
          { "amount": 560, "type_id": 9838 },
          { "amount": 560, "type_id": 2317 }
        ],
        "last_update": "2019-02-28T22:09:51Z",
        "type_id": 2544
      }
    }
  }
}

标签: javascriptnode.jsimmutability

解决方案


推荐阅读