После вызова API у меня есть данные в формате JSON. В этом формате существует массив с подчастями (извиняюсь, я не знаю терминологии), которые существуют внутри каждого ключа массива.
{
"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>"
}
}
]
}
В частности, я хочу создать отдельные массивы для всех имен смайлов, идентификаторов смайлов и типов файлов, например (я планирую иметь гораздо больше, чем эти два)
var emotecodes = [code0, code1, ...];
var emoteids = [id0, id1, ...];
var emotefiletypes = [imageType0, imageType1, ...];
Я пробовал разные вещи, которые нашел в Интернете, но безуспешно.
Вы можете использовать функцию уменьшения свойства sharedEmotes
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.info(formattedData.emotecodes, formattedData.emoteids, formattedData.emotefiletypes)
Чтобы создать отдельные массивы для имен эмоций, идентификаторов эмоций и типов файлов из данных JSON, вы можете использовать функцию map
в JavaScript. Функция map
позволит вам извлекать определенные части данных JSON и создавать новые массивы на основе этих частей.
const emotecodes = data.sharedEmotes.map(emote => emote.code);
const emoteids = data.sharedEmotes.map(emote => emote.id);
const emotefiletypes = data.sharedEmotes.map(emote => emote.imageType)
Вам нужно объяснить свой код, чтобы ОП его понял. См. Как ответить
@thecodingsage - честно говоря, ОП не опубликовал НЕТ кода, я думаю, что ответ соответствует уровню усилий в вопросе: p
Вот старомодный способ получить ваши данные. (НА)):
const getData = (json, type) => {
let result = []
for (let i of json['sharedEmotes']) {
result.push(i[type])
}
return result
}
Он просто перебирает массивsharedEmotes и помещает тип в новый массив.
И вот полный код:
const json = {
"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 getData = (json, type) => {
let result = []
for (let i of json['sharedEmotes']) {
result.push(i[type])
}
return result
}
let emotecodes = getData(json, 'code');
let emoteids = getData(json, 'id');
let emotefiletypes = getData(json, 'imageType');
console.info(emotecodes)
console.info(emoteids)
console.info(emotefiletypes)
Array.prototype.map() метод выполнит всю работу. Также рассмотрите возможность использования const
или let
для объявления переменных вместо var
( Вот вот почему).
const apiJSONData = {
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 emoteCodes = apiJSONData.sharedEmotes.map((emoteObj) => emoteObj.code);
const emoteIds = apiJSONData.sharedEmotes.map((emoteObj) => emoteObj.id);
const emoteFileTypes = apiJSONData.sharedEmotes.map(
(emoteObj) => emoteObj.imageType
);
console.info(emoteCodes);
console.info(emoteIds);
console.info(emoteFileTypes);
Это будет работать, но это решение трижды повторяет массив для одной и той же работы, которую можно выполнить за одну итерацию. Альтернативно, вы также можете использовать обычный for..loop
Ты прав; традиционный for...loop
действительно может быть более производительным для итераций с большим объемом данных, поскольку он позволяет избежать нескольких проходов по массиву. Однако современные методы массивов (forEach
, map
, filter
и т. д.) предлагают более читаемый и выразительный код, который четко передает намерение и его легче поддерживать. Во многих случаях читаемость и ясность, обеспечиваемые этими методами, перевешивают небольшую разницу в производительности, но всегда полезно учитывать конкретный контекст.
I've tried various other things
кроме чего? Ты ничего не сделал!