Reputation: 35
I'm trying to convert the following array into something JSON can understand and be able to append the same key/value pair to each array of objects, but I'm getting stuck on how to go about it.
Given the following array of objects:
{
"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": ""
}
]
}
I need to add the following to each array:
{Title : "title", id : "idNum"}
So that it reads like:
{
"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"
},
etc.
I'm not even sure if this is actually an array of object arrays, as I'm admittedly guessing a bit on the terminology. Eventually, I need this to be able to be processed as a JSON object for submitting to a SharePoint list using AJAX.
Would I need to loop through each array within the array and then add the object key/value pairs?
Upvotes: 0
Views: 2812
Reputation: 18515
You can use Array.map
and spread
and not mutate the original array:
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)
Upvotes: 5