【问题标题】:Reformat Existing JSON into new JSON using Javascript/Typescript使用 Javascript/Typescript 将现有 JSON 重新格式化为新 JSON
【发布时间】:2019-03-13 19:34:13
【问题描述】:

我目前有一个现有的 JSON,我想将其更改/重新格式化为新的 JSON,以便能够在外部服务中使用。格式有点复杂,但我无法更改,所以我必须编辑现有的 JSON。匹配我想要的输出。

现有 JSON:

{
    "specifiers": [{
        "value": "test",
        "type": "text",
        "label": "Brand ID"
    }, {
        "value": "test",
        "type": "text",
        "label": "Program ID"
    }]
}

所需的输出:


{
    "specifiers": {
        "Brand ID": {
            "text": {
                "value": "test",
                "type": "text"
            }
        },

        "Program ID": {
            "text": {
                "value": "test",
                "type": "text"
            }
        }
    }
}

我尝试过使用循环遍历现有 JSON,但我真的不知道如何格式化我的循环以使用值作为键?我猜我可能必须使用 Object.keys 或 Object.values,但我不确定如何获取特定键的特定值。

示例格式:

        "[label]": {
            "[type]": {
                "value": [value],
                "type": [type]
            }
        }

【问题讨论】:

  • 所以你总是以相同的输入格式接收它并希望将其转换为相同的输出格式?
  • 第一个选项是 imo 结构更好。之所以?除非您提前知道“说明符”包含“品牌 ID”和“程序 ID”属性(类似于您知道“文档”包含“querySelector”和“getElementById”方法),否则您将不得不遍历对象的属性,在这种情况下,您不妨使用数组。但是,没有考虑 API 的要求。

标签: javascript json typescript iteration reformatting


【解决方案1】:

function tranform({specifiers}) {
  return { specifiers: specifiers.reduce((obj, {label, type, value}) => ({...obj, [label]: { [type]: { type, value } } }), {}) }
}

const json = {
    "specifiers": [{
        "value": "test",
        "type": "text",
        "label": "Brand ID"
    }, {
        "value": "test",
        "type": "text",
        "label": "Program ID"
    }]
}

console.log(tranform(json))

【讨论】:

  • 为什么不用map 而不是reduce?
  • @BrunoEly 映射变换数组的子元素并返回新数组(带有变换后的子元素),但 OP 需要一个对象而不是数组
  • 你说得对,我一度认为specifiers 是输出中的一个数组
【解决方案2】:

reduce 非常简单:

const formattedSpecifiers = existingJSON.specifiers.reduce((newSpecifiers, specifier) => {
  newSpecifiers[specifier.label] = {
      [specifier.type]: {
        type: specifier.type,
        value: specifier.value,
      },
    };
  };

  return newSpecifiers;
}, {});

const newJSON = { specifiers: formattedSpecifiers };

【讨论】:

    【解决方案3】:

    您可以使用#Array.reduce。 sn-p 下面。

    let input = {
      "specifiers": [{
        "value": "test",
        "type": "text",
        "label": "Brand ID"
      }, {
        "value": "test",
        "type": "text",
        "label": "Program ID"
      }]
    }
    const res = input.specifiers.reduce((res, obj) => {
      const {
        label,
        type,
        value
      } = obj
      res[label] = {};
      res[label][type] = {
        value,
        type
      };
      return res;
    }, {});
    console.log(res);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 2016-06-27
      • 2021-12-18
      相关资源
      最近更新 更多