Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Merge different Array variables value into JSON Object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"BillDetails" : [{billsystem: "PizzaHut" , billnum: "12345"}, {billsystem : "Subway" , billnum "96754" }, {billsystem : "Subway" , billnum "75432"},{billsystem : "XYZ" , billnum "63946"}]}

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading