I am still learning JavaScript, so I apologize in advance if this seems a remedial question.
I am receiving data from an API call in the form of an array, like so:
arr = ['topic1',497,'topic2',591,'topic3',17,'topic4',980]
Though it's not evident from that array, the number following each topic string is the count of the previous topic.
I want to work with this data in a React app, i.e., map it to a table or other data structure. But that's exceedingly difficult to do when the values are anonymous like this.
So, I want to take this array and convert it into an object with key/value pairs. So, after working some kind of loop/filter/map/etc. on the array, I need to end up with this:
newArr = [
{topic: 'topic1', count: 497},
{topic: 'topic2', count: 591},
{topic: 'topic3', count: 17},
{topic: 'topic4', count: 980},
]
I have tried SO many techniques, ranging from using dictionaries, Maps, map, filter, forEach, for ... in, and more techniques than I even remember at this point. And yes, I searched many web pages and forums. The problem is, my question includes some of the very building blocks of JavaScript, so the answers I found were never specific enough for my problem.
I did successfully filter out the even and odd elements in the array, like so:
let x = arr.filter((element, index) => {
return index % 2 === 0; filter elements located at an even index
});
let y = arr.filter((element, index) => {
return index % 2 === 1; filter elements located at an odd index
});
But I've never successfully gotten the result I need. Can anybody please help point me in the right direction?
I'm using React, so feel free to suggest modern JS techniques. Thanks!