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

Monday, December 12, 2022

[FIXED] How to modify javascript array of objects like object values as key value pair

 December 12, 2022     arrays, data-structures, javascript, json, reactjs   

Issue

I am new to JavaScript programming and react. I have a data structure which I converted using the array.reduce method to the below given array.

My objective is to get the array re-structured in-order to use this is in a chart to visualize the data using react chart js 2.

const charData = [
    {
        "year": "2020",
        "value": [
            {
                "levelName": "Platinum",
                "yearlyCount": "1074"
            },
            {
                "levelName": "Gold",
                "yearlyCount": "1847"
            },
            {
                "levelName": "Silver",
                "yearlyCount": "4804"
            }
        ]
    }
]

i need the below structure

[
{
"year": "2020",
"Platinum": "1074",
"Gold": "1847",
"silver": "4804"
}
]

Solution

use map with reduce

const charData =  [
    {
        "year": "2020",
        "value": [
            {
                "levelName": "Platinum",
                "yearlyCount": "1074"
            },
            {
                "levelName": "Gold",
                "yearlyCount": "1847"
            },
            {
                "levelName": "Silver",
                "yearlyCount": "4804"
            }
        ]
    }
]

const res = charData.map(item => {
  const subRes = item.value.reduce((acc,i) => {
    return {
     ...acc,
     [i.levelName]  : i.yearlyCount
     
    }
  }, {})
  
  return {
    year: item.year,
    ...subRes,
  }
  
})

console.log(res)



Answered By - Sachila Ranawaka
Answer Checked By - - Mary Flores (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