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

javascript looping over data and recreating a data structure

If I have data like this:

{
"zone_temps" : {
   "VAV1": "read 12345:2 analogInput 2",
   "VAV2": "read 12345:2 analogInput 1",
   "VAV3": "read 12345:2 analogInput 1",
   "VAV4": "read 12345:2 analogInput 2",
   "VAV5": "read 12345:2 analogInput 1",
   "VAV6": "read 12345:2 analogInput 2",
   "VAV7": "read 12345:2 analogInput 1",   
   "VAV8": "read 12345:2 analogInput 1",   
   "VAV9": "read 12345:2 analogInput 2",   
   "VAV10": "read 12345:2 analogInput 1"}
}

Could someone give me a tip what a javascript function would look like looping over the data and recreating the data structure with same keys but the values would be in integer made from math.random()

Hopefully that makes sense, looking for a final output like this:

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

{
"zone_temps" : {
   "VAV1": "66",
   "VAV2": "88",
   "VAV3": "55",
   "VAV4": "66",
   "VAV5": "77",
   "VAV6": "67",
   "VAV7": "79",   
   "VAV8": "87",   
   "VAV9": "75",   
   "VAV10": "71"}
}

>Solution :

The English in the question is almost the answer in JS: Loop over the keys (map()) producing key-value pairs with random (Math.random()) values. Object.fromEntries() combines those pairs into a new object

const temps = {
  "VAV1": "read 12345:2 analogInput 2",
  "VAV2": "read 12345:2 analogInput 1",
  "VAV3": "read 12345:2 analogInput 1",
  "VAV4": "read 12345:2 analogInput 2",
  "VAV5": "read 12345:2 analogInput 1",
  "VAV6": "read 12345:2 analogInput 2",
  "VAV7": "read 12345:2 analogInput 1",
  "VAV8": "read 12345:2 analogInput 1",
  "VAV9": "read 12345:2 analogInput 2",
  "VAV10": "read 12345:2 analogInput 1"
}

const result = Object.fromEntries(Object.keys(temps).map(key => {
  return [ key, Math.round(Math.random()*100) ]
}))

console.log(result)
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