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

Transform Object to array with new keys in reactJs

I have an output from my return Object like the below:

{
    "note_1": 14,
    "note_2": 0,
    "note_3": 5,
    "note_4": 17,
    "note_5": 22
}

I need to transform this into a new Array where i would need to add values from the above into new keys like the below structure and order reversed

[
    {note: 5, count: 22},
    {note: 4, count: 17},
    {note: 3, count: 5},
    {note: 2, count: 0},
    {note: 1, count: 14}
]

I have tried to target the last character of the object key to get the note by using the charAt() function (dont know if it’s the best way to do 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

let distribution = [];

if (props.distribution()) {
    const notes = Object.values(props.distribution).map(item => {
        return item.charAt(item.length-1)
    });
    distribution = Array.from(
        notes.reduce((r, c) => r, new Map()),
        (([note, count]) => ({ note, count }))
    )
}

>Solution :

const obj = {
    "note_1": 14,
    "note_2": 0,
    "note_3": 5,
    "note_4": 17,
    "note_5": 22
}

const transformed = Object.keys(obj).map(key => {
  const sp = key.split('_');
  const noteVal = sp[1];
  return {
    note: Number(noteVal),
    count: Number(obj[key])
  };
})
console.log(transformed)
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