Getting array of one variable per object from API

时间:2018-05-09 02:47:54

标签: javascript jquery json ajax

So I have the following in my API:

{
"rooms": [
    {
       "id": "01fa01fa5f685563",
      "name": "Main Bedroom",
      "meta": "{bedroom}"
    },
    {
      "id": "7bb6f6ec4dbed853",
      "name": "Laundry Room",
      "meta": "{laundry}"
    }
  ]
}

So now I want to get all the names under 'rooms' (in this case it would be "Main Bedroom" and "Laundry Room") as an array.

I have two .js files One is called api.js

var api = class {
    static get baseUrl() {
    return "http://127.0.0.1:8080/api/";
  }

  static get timeout() {
    return 60 * 1000;
  }
}

api.rooms = class {
  static get url() {
    return api.baseUrl + "rooms/";
  }

  static getRooms() {
       return $.ajax({
            url: api.room.url,
            method: "GET",
            dataType: "json",
            timeout: api.timeout
             .then(function(data) {
                 data.rooms.map(item => item.name);
               })

          }); 
    }
}

And then I have another .js called rooms.js where I want to call this getRooms() function and then do something with the array of names I want to get from it. How can I do this??? I though of something as simple as:

    $(document).ready(function() {

          $("#title").text(api.rooms.getRooms()[0]);

   });

I'm just starting with APIs and JSON and that stuff. If anyone has a good tutorial I can watch or read it would be appreciated as well.

1 个答案:

答案 0 :(得分:2)

Use Array#map for this. It iterates through the array and maps each element to the return value.

const data = {
  "rooms": [{
      "id": "01fa01fa5f685563",
      "name": "Main Bedroom",
      "meta": "{bedroom}"
    },
    {
      "id": "7bb6f6ec4dbed853",
      "name": "Laundry Room",
      "meta": "{laundry}"
    }
  ]
};

const result = data.rooms.map(item => item.name);
console.log(result);


Edit 1:

Your getRooms() function seems okay (assuming the value for URL and timeout are correct), but you need to use then() to get results from it:

getRooms()
  .then(function(data) {
    data.rooms.map( ... );
  })