After calling an API, I have some data in JSON format. Within that format, there is an array with sub-parts (I apologize, I don’t know the terminology) that exist inside each key of the array.
{
"id": "<my id>",
"bots": [],
"avatar": "https://static-cdn.jtvnw.net/jtv_user_pictures/1c1c09ef-3937-4408-8f31-04ec6bec2238-profile_image-300x300.png",
"channelEmotes": [],
"sharedEmotes": [
{
"id": "<emote id>",
"code": "<emote name>",
"imageType": "<filetype>",
"animated": true,
"user": {
"id": "<emote creator id>",
"name": "<emote creator username>",
"displayName": "<emote creator display name>",
"providerId": "<not sure what this field is actually>"
}
},
{
"id": "<emote id>",
"code": "<emote name>",
"imageType": "<filetype>",
"animated": true,
"user": {
"id": "<emote creator id>",
"name": "<emote creator username>",
"displayName": "<emote creator display name>",
"providerId": "<not sure what this field is actually>"
}
}
]
}
Specifically, I want to make separate arrays for all the emote name, emote id, and filetypes like (I plan to have many more than these two)
var emotecodes = [code0, code1, ...];
var emoteids = [id0, id1, ...];
var emotefiletypes = [imageType0, imageType1, ...];
I’ve tried various other things I’ve found around the internet but have had no success.
4
Answers
You can use the reduce function on the
sharedEmotes
property of the jsonTo create separate arrays for the emote names, emote ids, and filetypes from the JSON data, you can use the
map
function in JavaScript. Themap
function will allow you to extract specific parts of the JSON data and create new arrays based on those parts.Here is a old fashioned way to get your data. (O(N)):
It just iterates over the sharedEmotes array and push the type into a new array.
And here is the full code:
Array.prototype.map() method would do the work. Also consider using
const
orlet
to declare variables instead ofvar
(Here is why).