L oop через JavaScript Объект и суб-объекты - PullRequest
0 голосов
/ 01 августа 2020

Я пытаюсь получить oop через ответ API. Мой код на данный момент:

async function getStreams(gamename){ 
  let url = `https://api.twitch.tv/kraken/streams/?game=${gamename}`;
  const response = await fetch(url,{ method: 'GET', headers: headers});
  const json =  await response.json();
  var test = Object.values(json)
});

тестовая переменная возвращает объект типа this .

необработанный ответ выглядит как this .

Поскольку все, что меня интересует, находится под streams, я не уверен, как разделить каждый поток, а затем проверить каждый аспект, такой как channels.language ключ.

Мне казалось, что я почти было это со следующим:

Object.values(json).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object 
  console.log(key)
});

Однако теперь мне нужно go глубже в ключ - key.values, key[0], и что-то подобное не сработает. Мне нужно l oop через весь указанный ключ и проверить, есть ли language === 'de', а затем распечатать весь ключ / объект. Поскольку тег language находится в другом подобъекте channel внутри него, я не понимаю, что использовать.

Ответы [ 4 ]

1 голос
/ 01 августа 2020

Разбейте проблему. streams - это массив объектов. Вы можете отфильтровать их на основе языковых параметров из channel.

const germanChannels = streams.filter(stream => stream.channel.language === 'de');
0 голосов
/ 01 августа 2020

Вот быстрое решение:

Object.keys(jsonData).forEach(function(key) {
    var values = jsonData[key];
    values.forEach(obj => {
      console.log(obj.channel.language);
      if(obj.channel.language === 'de') {
      // apply custom logic or in-depth filters here
      console.log(obj); 
      }
    })
});
0 голосов
/ 01 августа 2020

Вот как использовать утилиту Prop Filter:

let toString = Object.prototype.toString;

// strict object check
function isObject(value) {
  return toString.call(value) === '[object Object]';
}

// strict array check
function isArray(value) {
  return toString.call(value) === '[object Array]';
}

function propPicker(data = {}, props = []) {
  // type guard for props parameter
  // ensure it is an array
  if (!isArray(props)) {
    throw new TypeError('Second parameter must be an array');
  }

  // type guard for data parameter
  // ensure it is an object
  if (!isObject(data)) {
    throw new TypeError('first parameter must be an object');
  }

  // the object or result to return
  let output = {};

  // iterate through data
  // to pick properties
  Object.keys(data).forEach(key => {
    // add key (property) to the result to be
    // returned if it is present on the
    // data object
    if (props.includes(key)) {
      output[key] = data[key];
    }

    // recursive traverse the key (property)
    // if it is an object
    else if (isObject(data[key])) {
      let selectedProps = propPicker(data[key], props);
      let obj;

      // add keys (properties) from nested object
      // if the key is present on the data object
      if (Object.keys(selectedProps).length) {
        obj = {
          [key]: selectedProps,
        };
      }

      // merge main object and keys with
      // nested objects with filtered keys
      output = Object.assign({}, output, obj);
    }
  });

  return output;
}



const streamsObject = {
    "streams": [
        {
            "_id": 209427714,
            "game": "VALORANT",
            "broadcast_platform": "live",
            "community_id": "",
            "community_ids": [],
            "viewers": 18874,
            "video_height": 1080,
            "average_fps": 60,
            "delay": 0,
            "created_at": "2020-08-01T13:30:04Z",
            "is_playlist": false,
            "stream_type": "live",
            "preview": {
                "small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_mandatory-80x45.jpg",
                "medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_mandatory-320x180.jpg",
                "large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_mandatory-640x360.jpg",
                "template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_mandatory-{width}x{height}.jpg"
            },
            "channel": {
                "mature": false,
                "status": "IGNITION SERIES x MANDATORY.GG CUP - DAY 2 - QUARTER FINALS - NiP 1 - 1 Those Guys",
                "broadcaster_language": "en",
                "broadcaster_software": "",
                "display_name": "Mandatory",
                "game": "VALORANT",
                "language": "fr",
                "_id": 514026431,
                "name": "mandatory",
                "created_at": "2020-04-14T13:33:08.208742Z",
                "updated_at": "2020-08-01T16:33:34.993381Z",
                "partner": true,
                "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/ffd17c21-5333-4817-8376-0c0df97e97bb-profile_image-300x300.png",
                "video_banner": null,
                "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/762a158e-4cc9-40a5-9fbd-a3d1bfbb4360-profile_banner-480.png",
                "profile_banner_background_color": "",
                "url": "https://www.twitch.tv/mandatory",
                "views": 158550,
                "followers": 8280,
                "broadcaster_type": "",
                "description": "Welcome on Mandatory.GG official Twitch channel ! We're a 100% Valorant community.",
                "private_video": false,
                "privacy_options_enabled": false
            }
        },
        {
            "_id": 209051778,
            "game": "VALORANT",
            "broadcast_platform": "live",
            "community_id": "",
            "community_ids": [],
            "viewers": 15453,
            "video_height": 1080,
            "average_fps": 60,
            "delay": 0,
            "created_at": "2020-08-01T12:48:03Z",
            "is_playlist": false,
            "stream_type": "live",
            "preview": {
                "small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_zerator-80x45.jpg",
                "medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_zerator-320x180.jpg",
                "large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_zerator-640x360.jpg",
                "template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_zerator-{width}x{height}.jpg"
            },
            "channel": {
                "mature": true,
                "status": "IGNITION SERIES x MANDATORY.GG CUP - DEMI-FINALE #1 [BO3] - G2 ESPORTS 0 - 0 BBL ESPORTS",
                "broadcaster_language": "fr",
                "broadcaster_software": "",
                "display_name": "ZeratoR",
                "game": "VALORANT",
                "language": "fr",
                "_id": 41719107,
                "name": "zerator",
                "created_at": "2013-03-25T23:44:28.227952Z",
                "updated_at": "2020-08-01T16:29:35.684905Z",
                "partner": true,
                "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/599b546a-c27f-4684-93ff-5eeecd01fb2b-profile_image-300x300.png",
                "video_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/ea5ccb61-1bc8-44bd-9840-4f24489b3126-channel_offline_image-1920x1080.jpeg",
                "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/77e1f053-e6f9-4b90-8872-b0935a43ad3c-profile_banner-480.jpeg",
                "profile_banner_background_color": "",
                "url": "https://www.twitch.tv/zerator",
                "views": 92693955,
                "followers": 875927,
                "broadcaster_type": "",
                "description": "French Independent Streamer // contact : @tpdach on twitter or dach@zerator.tv",
                "private_video": false,
                "privacy_options_enabled": false
            }
        },
        {
            "_id": 2360043473,
            "game": "VALORANT",
            "broadcast_platform": "live",
            "community_id": "",
            "community_ids": [],
            "viewers": 3043,
            "video_height": 1080,
            "average_fps": 60,
            "delay": 0,
            "created_at": "2020-08-01T09:19:04Z",
            "is_playlist": false,
            "stream_type": "live",
            "preview": {
                "small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_hastad-80x45.jpg",
                "medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_hastad-320x180.jpg",
                "large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_hastad-640x360.jpg",
                "template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_hastad-{width}x{height}.jpg"
            },
            "channel": {
                "mature": false,
                "status": "HASTAD - RADIANTE - i love you hachi s2",
                "broadcaster_language": "pt",
                "broadcaster_software": "",
                "display_name": "hastad",
                "game": "VALORANT",
                "language": "pt-br",
                "_id": 26857029,
                "name": "hastad",
                "created_at": "2011-12-18T00:05:08.641512Z",
                "updated_at": "2020-08-01T16:30:04.644868Z",
                "partner": true,
                "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/6b23888a-0500-49ec-99fa-4e89c721f3bc-profile_image-300x300.png",
                "video_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/646ab44cadea492b-channel_offline_image-1920x1080.png",
                "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/a6f2ef1d-1e37-481c-838a-7f18c53d1c16-profile_banner-480.png",
                "profile_banner_background_color": "",
                "url": "https://www.twitch.tv/hastad",
                "views": 45423892,
                "followers": 848327,
                "broadcaster_type": "",
                "description": "hastad - RADIANT - VALORANT PLAYER - RAZE IS MY MAINLIVES TODOS OS DIAS 9AM ATÉ 9PM",
                "private_video": false,
                "privacy_options_enabled": false
            }
        },
        {
            "_id": 2360274689,
            "game": "VALORANT",
            "broadcast_platform": "live",
            "community_id": "",
            "community_ids": [],
            "viewers": 1607,
            "video_height": 1080,
            "average_fps": 60,
            "delay": 0,
            "created_at": "2020-08-01T13:10:26Z",
            "is_playlist": false,
            "stream_type": "live",
            "preview": {
                "small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_sacy-80x45.jpg",
                "medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_sacy-320x180.jpg",
                "large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_sacy-640x360.jpg",
                "template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_sacy-{width}x{height}.jpg"
            },
            "channel": {
                "mature": false,
                "status": "SACY - RANKED RADIANTE - !loja !youtube",
                "broadcaster_language": "pt",
                "broadcaster_software": "",
                "display_name": "sacy",
                "game": "VALORANT",
                "language": "pt-br",
                "_id": 25116812,
                "name": "sacy",
                "created_at": "2011-09-27T23:29:45.144335Z",
                "updated_at": "2020-08-01T16:29:55.624657Z",
                "partner": true,
                "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/33aaee2d-750b-4020-94b1-6f2633d86c41-profile_image-300x300.png",
                "video_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/bf58561f-707d-48a6-a23c-8af0c4b2b0f3-channel_offline_image-1920x1080.png",
                "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/779f4cbf-4dd6-4f2e-9c5a-d754dc42469c-profile_banner-480.png",
                "profile_banner_background_color": "",
                "url": "https://www.twitch.tv/sacy",
                "views": 5775708,
                "followers": 199173,
                "broadcaster_type": "",
                "description": "",
                "private_video": false,
                "privacy_options_enabled": false
            }
        },
        {
            "_id": 210846322,
            "game": "VALORANT",
            "broadcast_platform": "live",
            "community_id": "",
            "community_ids": [],
            "viewers": 1533,
            "video_height": 1080,
            "average_fps": 60,
            "delay": 0,
            "created_at": "2020-08-01T16:08:33Z",
            "is_playlist": false,
            "stream_type": "live",
            "preview": {
                "small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_blackelespanolito-80x45.jpg",
                "medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_blackelespanolito-320x180.jpg",
                "large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_blackelespanolito-640x360.jpg",
                "template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_blackelespanolito-{width}x{height}.jpg"
            },
            "channel": {
                "mature": false,
                "status": "SUBIENDO A INMORTAL ANTES DE QUE ACABE EL ACTO | 3 DIAS",
                "broadcaster_language": "es",
                "broadcaster_software": "",
                "display_name": "blackelespanolito",
                "game": "VALORANT",
                "language": "es",
                "_id": 68124914,
                "name": "blackelespanolito",
                "created_at": "2014-08-04T04:27:31.572115Z",
                "updated_at": "2020-08-01T16:29:52.636507Z",
                "partner": true,
                "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/22543fff-bfc5-4133-bfd3-75557a5e35ce-profile_image-300x300.png",
                "video_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/d5fb2d77-1d31-43f6-8b51-0c98ec5b5c8f-channel_offline_image-1920x1080.png",
                "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/574995b0-4ada-4329-92bb-db5a9ef9e924-profile_banner-480.png",
                "profile_banner_background_color": "",
                "url": "https://www.twitch.tv/blackelespanolito",
                "views": 9858458,
                "followers": 309222,
                "broadcaster_type": "",
                "description": "CS:GO Y VALORANT 24/7",
                "private_video": false,
                "privacy_options_enabled": false
            }
        },
        {
            "_id": 3921422817798718623,
            "game": "VALORANT",
            "broadcast_platform": "live",
            "community_id": "",
            "community_ids": [],
            "viewers": 1454,
            "video_height": 1080,
            "average_fps": 60,
            "delay": 0,
            "created_at": "2020-08-01T13:34:45Z",
            "is_playlist": false,
            "stream_type": "live",
            "preview": {
                "small": "https://static-cdn.jtvnw.net/previews-ttv/live_user_jasonr-80x45.jpg",
                "medium": "https://static-cdn.jtvnw.net/previews-ttv/live_user_jasonr-320x180.jpg",
                "large": "https://static-cdn.jtvnw.net/previews-ttv/live_user_jasonr-640x360.jpg",
                "template": "https://static-cdn.jtvnw.net/previews-ttv/live_user_jasonr-{width}x{height}.jpg"
            },
            "channel": {
                "mature": false,
                "status": "100T VS BBG",
                "broadcaster_language": "en",
                "broadcaster_software": "",
                "display_name": "JASONR",
                "game": "VALORANT",
                "language": "en",
                "_id": 103262684,
                "name": "jasonr",
                "created_at": "2015-09-29T06:06:05.814442Z",
                "updated_at": "2020-08-01T16:49:15.189364Z",
                "partner": true,
                "logo": "https://static-cdn.jtvnw.net/jtv_user_pictures/4a5c1148-a148-4849-a2a8-656dc73d52ea-profile_image-300x300.png",
                "video_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/22d82e7e-0531-4790-897d-6e2078cf95e6-channel_offline_image-1920x1080.png",
                "profile_banner": "https://static-cdn.jtvnw.net/jtv_user_pictures/7f04e0b5-7e59-4c29-90cc-847db3dbedfc-profile_banner-480.png",
                "profile_banner_background_color": "",
                "url": "https://www.twitch.tv/jasonr",
                "views": 36354582,
                "followers": 772580,
                "broadcaster_type": "",
                "description": "bangin",
                "private_video": false,
                "privacy_options_enabled": false
            }
        }
    ]
}


streamsObject.streams.forEach(stream => {
  let channelObj = propPicker(stream, ["language"])
  if (channelObj.channel && channelObj.channel.language && channelObj.channel.language == "fr") {
  console.log(stream)
}
})
0 голосов
/ 01 августа 2020

Object.values дает вам значения , не ключи (это будет Object.keys; имеет смысл?) - если значение является объектом, вы получите этот объект в первом параметре. Таким образом, если вы хотите распечатать объект if channel.language === 'de' из этого объекта потока, это так же просто, как следующее:

Object.streams.values(json).forEach(function (value) {
  // value: the **value** of the object key
  if (value.channel.language === 'de') console.log(value);
});

(Кроме того, вы хотите перебирать свойство streams, а не свойство JSON сам.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...