0

I have an array of houses which has an array of rooms inside.

Each room, house and street has a unique ID (eg: if rooms in house 1 has id 1..4, rooms in house 2 will have id 5..9)

var street = {
    id = 1,
    streetname = 'stack street',
    houses = [
        {
            id: 1,
            type: 'brick'
            rooms: [
                {
                    id: 1,
                    color: 'blue'
                }, ... a bunch more
            ]
        }, ... a bunch more
    ]
}

Are there easy solutions like arr.findIndex() for:
1) Given a room id, return the index of the house in array houses, and index of the room in array rooms of that house
2) Given a room id, return the house it's in
3) Given a room id, return the room object

Friedpanseller
  • 654
  • 3
  • 16
  • 31
  • Start here: https://stackoverflow.com/questions/8517089/js-search-in-object-values or search around other questions for finding an array (of objects) index by searching contained values. – S.. Jan 02 '19 at 05:45

2 Answers2

2

1) The findIndex() is that easy solution but you need to employ an array function once more to scan through rooms within the house check callback:

var houseIndex = street.houses.findIndex(h => h.rooms.some(r => r.id === roomId));

2) Just the same with find():

var house = street.houses.find(h => h.rooms.some(r => r.id === roomId));

or if the earlier index lookup is in place, use its result:

var house = street.houses[houseIndex];

3) Flatten the house-room hierarchy into a plain room list and search it for the desired room:

var room = street.houses.flatMap(h => h.rooms).find(r => r.id === roomId);
Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
0

For room id 7:

1)

int houseIndex = street.houses.findIndex(house => house.rooms.find(room => room.id == 7));
int roomIndex = street.houses.find(house => house.rooms.find(room => room.id == 7)).rooms.findIndex(room => room.id == 7)

2)

var houseObject = street.houses.find(house => house.rooms.find(room => room.id == 7))  

3)

var roomObject = street.houses.find(house => house.rooms.find(room => room.id == 7)).rooms.find(room => room.id == 7)
Friedpanseller
  • 654
  • 3
  • 16
  • 31