gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:08:22 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com