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

How to make {value,array[i]} object pairs in javascript

I’m receiving from backend side object which is formulated like:

[
  {value: 'FIRST', AvailableValues[{code: "one"},{code: "two"}]},
  {value: 'SECOND', AvailableValues[{code: "one"},{code: "two"}]
]

My question is how to map through this object to create pairs like

[{value: "FIRST", code:"one"}, 
{value: "FIRST", code:"two"},
{value: "SECOND", code:"one"},
{value: "SECOND", code:"two"}]

Thanks

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

I tried combination of javascript predefined methods like double map, keyed search and so on, but it resulted with errors

>Solution :

use reduce function

Also, your initial data should be an array because if it’s a object, then it should contains key with values

const list = [
  {value: 'FIRST', AvailableValues:[{code: "one"},{code: "two"}]},
  {value: 'SECOND', AvailableValues:[{code: "one"},{code: "two"}]}
]

const result = list.reduce((acc,item) => {
  const res = item.AvailableValues.map(i => ({value: item.value, code: i.code}))
  
  return [...acc,...res]
}, [])

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