![](/img/trans.png)
[英]How to reformat a Nested JSON and restructure using javascript
[英]Reformat Existing JSON into new JSON using Javascript/Typescript
我目前有一个现有的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))
用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 };
您可以使用#Array.reduce。 下面的代码段。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.