I have the following code which stores in an object the number of times an author is repeated in the tour array, but what is stored in the object is the name of the author as a key and the number of times it is repeated as a value, when what I want is to create a key called author and store the name of the author and a key called blogs and the number of times it is repeated.
This is what is stored in my object
{Michael Chan: 1, Edsger W. Dijkstra: 2, Robert C. Martin: 3}
But the result that I expect and that I cannot understand how to do it is the following
{
author: 'Michael Chan',
blogs: 1
},
{
author: 'Edsger W. Dijkstra',
blogs: 2
},
{
author: 'Robert C. Martin'
blogs: 3
}
Code in Codesandbox
I attach the code made which runs only in the console for checks.
One solution might be to use map() to map or "convert" an array with one structure to another with a different structure.
With Object.keys() we get the author names as an array (
["Michael Chan", "Edsger W. Dijkstra", "Robert C. Martin"]
).Once we have the array, we just map each value (each author) to the desired new structure with
map()
.Adding a for with value key, you build your object and assign it to the array, I hope it works for you
Another solution. In this, the author is searched in the list if it is, the blogs are increased and if not, a new entry is created in the list of authors. The search in the array of blogs is done by comparing the author fields of the entries in both lists. The entire operation is done at once, in a single loop.