Как получить доступ к каждому индексу определенного массива внутри объекта AJAX - PullRequest
0 голосов
/ 13 сентября 2018

Я звоню ajax для giphy, с таким кодом:

$.ajax({
  url: queryURL,
  method: "GET"
}). then(function(response) {
  console.log(response);

, когда я смотрю на журнал консоли, появляется объект с первым свойством, являющимся данными.Каждый индекс данных - это другой объект, внутри этого объекта есть два свойства, которые я пытаюсь получить, rating и url.Я хочу иметь возможность перечислять rating и url не только определенного индекса, но каждого индекса в этом массиве данных.Каков был бы лучший способ сделать это?В настоящее время я пробовал цикл for

for (var i = 0; i<response.data.length;i++){
  var dataIndex = response.data[i];
}  
then <creating a variable something like> 
  var imgURL = response.data[dataIndex].url

, но он не работает.

Вот весь код

function displayTopicGif() {
var topic = $(this).attr("data-name");
// query url
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&limit=20&rating=r&api_key=";

$.ajax({
    url: queryURL,
    method: "GET"
}).then(function (response) {
    console.log(response);
    // for loop to create a variable for the index of the objects data
    for (var i = 0; i < response.data.length; i++) {
        var dataIndex = response.data[i];

    }
    // where the gif's will be dumped
    var topicDiv = $("<div class='topic'>");
    // rating of gif
    var rating = response.data[0].rating;
    console.log(rating);
    // Creating an element to have the rating displayed
    var pOne = $("<p>").text("Rating: " + rating);
    // add to the rating element
    topicDiv.append(pOne);
    // retrieve the IMG of the gif

    var imgURL = response.data[0].url;

    var image = $("<img>").attr("src", imgURL);
    topicDiv.append(image);
    // put gif into topic-view div
    $("#topic-view").prepend(topicDiv);


});
}

1 Ответ

0 голосов
/ 13 сентября 2018

Вы можете проверить, что что-то является объектом, используя $. IsPlainObject , а затем прочитать его свойства с помощью:

for (key in object) {
   var value = object[key];
   //log
}

Или вы можете получить ключи, используя Object.getOwnPropertyNames (); . Смотрите этот пример выдержки из MDN:

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...