首页 > 解决方案 > 根据项目中的要求,将 json 对象数组解析为特定格式的 json 数组

问题描述

根据我在项目中的 requiremrnt,我得到了下面的 json 数组作为输入,但我需要将其转换为特定格式的 json 对象数组。

[
  {
    "accident_description": "bike accident",
    "reported_by": "john",

  },
   {
    "accident_description": "car accident",
    "reported_by": "sam",

  }
]

输出>>>

  "fields": [
    {
      "title": "accident_description",
      "values": "bike accident"
      "type": "generic",

    },
    {
      "title": "reported_by",
      "values": "john",
      "type": "generic",

    },
    {
      "title": "accident_description",
      "values": "car accident"
      "type": "generic",

    },
    {
      "title": "reported_by",
      "values": "sam",
      "type": "generic",

    },
  ]

标签: javascriptjson

解决方案


你可以像这样mapObject.entires每个对象:

const input=[{"accident_description":"bike accident","reported_by":"john",},{"accident_description":"car accident","reported_by":"sam",}],
      type = "generic";

const output = input.flatMap(Object.entries)
                    .map(([title, values]) => ({ title, values, type }))
     
console.log(output)


推荐阅读