javascript - 使用 Javascript/Typescript 将现有 JSON 重新格式化为新 JSON

标签 javascript json typescript iteration reformatting

我目前有一个现有的 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]
            }
        }

最佳答案

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))

关于javascript - 使用 Javascript/Typescript 将现有 JSON 重新格式化为新 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149937/

相关文章:

typescript - Webpack 无法找到 TypeScript(显然)找到的导入

json - 将 JSON 日期发送到 WCF 服务

javascript - Angular 翻译多个 json 文件

json - 为 JSON 配置 Tomcat 6

javascript - 有没有办法根据 json 对象中的特定项目查询数据?

带有字符串变量的 Angular 2 动态模板 url?

Angular 2在路由时传递对象

javascript - 使用 react 导航重新加载或重新渲染事件

javascript - 如何在源回调中检索 jQuery UI 自动完成?

javascript - 将值传递给正则表达式