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!)
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 }))
)
}
6
Answers
This should do it:
This is an option to accomplish that. I suggest you to use
slice(-1)
instead of charAt to get the last character.Edit:
You can actually use
at(-1)
, it is implemented in practically all relevant browsers now.If your note numbers can grow higher than 10, you’d better
split('_')[1]
and parse to numberUsing
reduce()
onObject.entries()
where wesplit()
the key to get the everything behindnote_
This works:
OUTPUT:
React JS does need to be mentioned here…
You only need JavaScript
for, Objecet.keys, split methods you need to use for this challenge.