ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Friday, December 16, 2022

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

 December 16, 2022     javascript, reactjs   

Issue

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

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)



Answered By - Sachila Ranawaka
Answer Checked By - - Katrina (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix