Saiteja
Saiteja

Reputation: 25

Find the array element that has a certain attribute value

Please consider the below object as example:

let roomsData = [{
  "room_ID": "100",
  "Seats_Available": 4,
  "Amenities": ["AC", "Hot Water"],
  "Price": "10000"
}, {
  "room_ID": "203",
  "Seats_Available": 6,
  "Amenities": ["AC", "Hot Water", "Washing"],
  "Price": "10000"
}, {
  "room_ID": "301",
  "Seats_Available": 4,
  "Amenities": ["Non AC", "Hot Water"],
  "Price": "10000"
}]

If we have have 100 as room ID (i.e the value) in above example with us then I want to get the output as the complete array element like below:

{
  "room_ID": "100",
  "Seats_Available": 4,
  "Amenities": ["AC", "Hot Water"],
  "Price": "10000"
}

Can you please explain if there is any solution for that?

Upvotes: 1

Views: 612

Answers (1)

ThS
ThS

Reputation: 4783

A quick solution is to use find to get the desired item based on an ID.

The find method loops through your data and returns the first matched element based on a callback function that you supply to it that should return true when the desired item is the current one.

Here's a live demo to illustrate all what's being said:

let roomsData = [{
      "room_ID": "100",
      "Seats_Available": 4,
      "Amenities": ["AC", "Hot Water"],
      "Price": "10000"
    },
    {
      "room_ID": "203",
      "Seats_Available": 6,
      "Amenities": ["AC", "Hot Water", "Washing"],
      "Price": "10000"
    },
    {
      "room_ID": "301",
      "Seats_Available": 4,
      "Amenities": ["Non AC", "Hot Water"],
      "Price": "10000"
    }
  ],
  /** 
  * get a room by its ID
  * return the item if found or "undefined" otherwise
  */
  getRoomById = roomID => roomsData.find(i => i.room_ID == roomID);

/** call that function */
console.log(getRoomById(1000));

The above code, precisely the call to getRoomById, should display:

{
  "room_ID": "100",
  "Seats_Available": 4,
  "Amenities": ["AC", "Hot Water"],
  "Price": "10000"
}

Upvotes: 1

Related Questions