I have below respective variables holding the bill# in an array.
billA = [12345] // For "Pizzahut" Billsystem
billB = [96754,75432] // For "Subway" Billsystem
billC = [63946] // For "XYZ" Billsystem
I intend to combine the above values into a JSON object like the below format.
Result Output:
{"BillDetails" : [{billsystem: "PizzaHut" , billnum: "12345"}, {billsystem : "Subway" , billnum "96754" }, {billsystem : "Subway" , billnum "75432"},{billsystem : "XYZ" , billnum "63946"}]}
CodePudding user response:
const obj = {
"BillDetails" : [
...billA.map(item=>({billsystem: "PizzaHut" , billnum: String(item)})),
...billB.map(item=>({billsystem: "Subway" , billnum: String(item)})),
...billC.map(item=>({billsystem: "XYZ" , billnum: String(item)})),
]
}
CodePudding user response:
You could use flatMap
along with an array of billing systems
let billA = [12345] // For "Pizzahut" Billsystem
let billB = [96754, 75432] // For "Subway" Billsystem
let billC = [63946] // For "XYZ" Billsystem
let billD = [] // For "Testing" Billsystem
let types = ["Pizzahut", "Subway", "XYZ", "Testing"]
let json = {
BillDetails: [billA, billB, billC, billD].flatMap((e, i) => (e?.map(b => ({
billSystem: types[i],
billNum: b
}))))
}
console.log(json)