映射对象键:值对到JSON的对象数组的数组

时间:2018-11-26 21:11:10

标签: javascript arrays json dictionary object

我正在尝试将以下数组转换成JSON可以理解的东西,并且能够将相同的键/值对附加到每个对象数组,但是我对如何使用它感到困惑。

给出以下对象数组:

{
  "array": [
    {
      "Type": "Current",
      "Item1": "3",
      "Item2": "23",
      "Item3": "90",
      "Item4": null,
      "Year": "2019",
      "Amount": "100"
    },
    {
      "Type": "Current",
      "Item1": "3",
      "Item2": "23",
      "Item3": "90",
      "Item4": null,
      "Year": "2020",
      "Amount": "200"
    },
    {
      "Type": "Current",
      "Item1": "3",
      "Item2": "23",
      "Item3": "90",
      "Item4": null,
      "Year": "2021",
      "Amount": "300"
    },
    {
      "Type": "Change",
      "Item1": null,
      "Item2": null,
      "Item3": null,
      "Item4": null,
      "Year": "2019"
    },
    {
      "Type": "Change",
      "Item1": null,
      "Item2": null,
      "Item3": null,
      "Item4": null,
      "Year": "2020",
      "Amount": ""
    },
    {
      "Type": "Change",
      "Item1": null,
      "Item2": null,
      "Item3": null,
      "Item4": null,
      "Year": "2021",
      "Amount": ""
    }
  ]
}

我需要在每个数组中添加以下内容:

{Title : "title", id : "idNum"}

因此它看起来像:

{
  "Title": "title",
  "ID": "idNum",
  "Type": "Current",
  "Item1": "3",
  "Item2": "23",
  "Item3": "90",
  "Item4": null,
  "Year": "2019",
  "Amount": "100"
},
{
  "Title": "title",
  "ID": "idNum",
  "Type": "Current",
  "Item1": "3",
  "Item2": "23",
  "Item3": "90",
  "Item4": null,
  "Year": "2020",
  "Amount": "200"
},

我什至不确定这是否实际上是对象数组的数组,因为我承认对术语有些猜测。最终,我需要能够将其作为JSON对象进行处理,以便使用AJAX提交到SharePoint列表。

我是否需要遍历数组中的每个数组,然后添加对象键/值对?

1 个答案:

答案 0 :(得分:4)

您可以使用Array.mapspread,并且突变原始数组:

const data = { "array": [ { "Type": "Current", "Item1": "3", "Item2": "23", "Item3": "90", "Item4": null, "Year": "2019", "Amount": "100" }, { "Type": "Current", "Item1": "3", "Item2": "23", "Item3": "90", "Item4": null, "Year": "2020", "Amount": "200" }, { "Type": "Current", "Item1": "3", "Item2": "23", "Item3": "90", "Item4": null, "Year": "2021", "Amount": "300" }, { "Type": "Change", "Item1": null, "Item2": null, "Item3": null, "Item4": null, "Year": "2019" }, { "Type": "Change", "Item1": null, "Item2": null, "Item3": null, "Item4": null, "Year": "2020", "Amount": "" }, { "Type": "Change", "Item1": null, "Item2": null, "Item3": null, "Item4": null, "Year": "2021", "Amount": "" } ] } 

result = data.array.map(x => ({ Title: 'Title', ID: 'idNum', ...x}))

console.log(result)