TypeScript - Take object out of array based on attribute value

后端 未结 5 1844
名媛妹妹
名媛妹妹 2020-12-29 00:54

My array looks like this:

array = [object {id: 1, value: \"itemname\"}, object {id: 2, value: \"itemname\"}, ...]

all my objects have the s

5条回答
  •  没有蜡笔的小新
    2020-12-29 01:30

    You'll have to loop over the array, but if you make a hashmap to link each id to an index and save that, you only have to do it once, so you can reference any objeft after that directly:

    var idReference = myArray.reduce(function( map, record, index ) {
        map[ record.id ] = index;
        return map;
    }, {});
    
    var objectWithId5 = myArray[ idReference["5"] ];
    

    This does assume all ids are unique though.

提交回复
热议问题