我有以下格式的对象键值。
{
"Code1": {
"char10": "ch1",
"number1": "1",
"text1": "txt1"
},
"Code2": {
"char2": "ch2",
"num2": "2"
},
"Code3": {
"text": "txt4"
}
}
想要转换成这种格式:
{
"Code1": [
{
"char10": "Toshiba",
"text1": "H",
"number1": "19"
}
],
"Code2": [
{
"char2": "Toshiba",
"num2": "19"
}
],
"Code3": [
{
"text": "test"
}
]
}
设法获得一些类似的响应,但不是我正在寻找的确切输出。
尝试了下面的代码片段,但它返回的格式比预期的不同。
Object.entries(payload).map((e) => ( { [e[0]]: e[1] } ))
用上面的片段回应:
[
{
"Code1": {
"char10": "ch1",
"number1": "1",
"text1": "txt1"
}
},
{
"Code2": {
"char2": "ch2",
"num2": "2"
}
},
{
"Code3": {
"text": "txt4"
}
}
]
您可以获取所有条目并映射新对象的包装值。
const
data = { Code1: { char10: "ch1", number1: "1", text1: "txt1" }, Code2: { char2: "ch2", num2: "2" }, Code3: { text: "txt4" } },
result = Object.fromEntries(Object
.entries(data)
.map(([k, v]) => [k, [v]])
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }