1

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?

3
  • 1
    stackoverflow.com/questions/2722159/… Commented Oct 5, 2022 at 13:04
  • Use find. (The linked question does the same with filter, returning all matching elements, but since you are looking for only one element anyway, find is the better way.) Commented Oct 5, 2022 at 13:14
  • There is no JSON in this question. What you have is a JavaScript Object, more specifically a JS Array Commented Oct 5, 2022 at 13:19

1 Answer 1

1

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

Comments

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.