将键值对象转换为对象数组

问题描述 投票:0回答:1

我有以下格式的对象键值。

{
    "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"
        }
    }
]
javascript arrays json object javascript-objects
1个回答
0
投票

您可以获取所有条目并映射新对象的包装值。

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; }

© www.soinside.com 2019 - 2024. All rights reserved.