0

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 Answer 1

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( ... );
  })
Sign up to request clarification or add additional context in comments.

1 Comment

@Stackoverflowed -- In the callback of map, instead of just returning the name, you can return an object containing id and name both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.