在数组数组中按ID查找对象的索引

时间:2019-01-02 05:40:03

标签: javascript arrays json reactjs object

我有一系列房子,里面有一系列房间。

每个房间,房屋和街道都有唯一的ID(例如:如果房屋1中的房间ID为1..4,房屋2中的房间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
    ]
}

有没有像arr.findIndex()这样的简单解决方案:
1)在给定房间ID的情况下,返回数组房屋中房屋的索引,以及该房屋数组中房屋的索引。
2)给定房间ID,退还其所在的房子
3)给定房间ID,返回房间对象

2 个答案:

答案 0 :(得分:0)

对于房间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)

答案 1 :(得分:0)

1)Private Sub SplitDateAndTime() Dim input = "11/9/201812:52:53 AM" Dim d As DateTime = DateTime.ParseExact(input, "M/d/yyyyhh:mm:ss tt", CultureInfo.InvariantCulture) Dim dateOnly As String = d.ToShortDateString Dim timeOnly As String = d.ToLongTimeString Debug.Print($"The date is {dateOnly} and the time is {timeOnly}") 'result The date is 11/9/2018 and the time is 12:52:53 AM End Sub 是一个简单的解决方案,但是您需要再次使用数组函数来扫描房屋检查回调中的房间:

findIndex()

2)与var houseIndex = street.houses.findIndex(h => h.rooms.some(r => r.id === roomId)); 相同:

find()

或如果先前的索引查找到位,则使用其结果:

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

3)将房屋房间层次化为普通房间列表,并在其中搜索所需的房间:

var house = street.houses[houseIndex];