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.
>Solution :
You can use the reduce function on the sharedEmotes property of the json
const jsonData = {
"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>"
}
}
]
};
const formattedData = jsonData.sharedEmotes.reduce((acc, curr) => {
acc.emotecodes.push(curr.code);
acc.emoteids.push(curr.id);
acc.emotefiletypes.push(curr.imageType);
return acc;
}, {
emotecodes: [],
emoteids: [],
emotefiletypes: []
});
console.log(formattedData.emotecodes, formattedData.emoteids, formattedData.emotefiletypes)