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?

CherryDT
  • 25,571
  • 5
  • 49
  • 74
Saiteja
  • 25
  • 5
  • 1
    https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes – CBroe Oct 05 '22 at 13:04
  • Use [`find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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.) – CherryDT Oct 05 '22 at 13:14
  • There is no JSON in this question. What you have is a JavaScript Object, more specifically a JS Array – phuzi Oct 05 '22 at 13:19

1 Answers1

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"
}
CherryDT
  • 25,571
  • 5
  • 49
  • 74
ThS
  • 4,597
  • 2
  • 15
  • 27