TypeScript - Take object out of array based on attribute value

后端 未结 5 1707
名媛妹妹
名媛妹妹 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:18

    I'd use filter or reduce:

    let array = [
        { id: 1, value: "itemname" },
        { id: 2, value: "itemname" }
    ];
    
    let item1 = array.filter(item => item.id === 1)[0];
    let item2 = array.reduce((prev, current) => prev || current.id === 1 ? current : null);
    
    console.log(item1); // Object {id: 1, value: "itemname"}
    console.log(item2); // Object {id: 1, value: "itemname"}
    

    (code in playground)

    If you care about iterating over the entire array then use some:

    let item;
    array.some(i => {
        if (i.id === 1) {
            item = i;
            return true;
        }
        return false;
    });
    

    (code in playground)

    0 讨论(0)
  • 2020-12-29 01:18

    You can search a certain value in array of objects using TypeScript dynamically if you need to search the value from all fields of the object without specifying column

     var searchText = 'first';
    
    let items = [
                { id: 1, name: "first", grade: "A" },
                { id: 2, name: "second", grade: "B" }
            ];
    
    This below code will search for the value
    
    var result = items.filter(item => 
                 Object.keys(item).some(k => item[k] != null && 
                 item[k].toString().toLowerCase()
                 .includes(searchText.toLowerCase()))
                 );
    

    Same approach can be used to make a Search Filter Pipe in angularjs 4 using TypeScript

    0 讨论(0)
  • 2020-12-29 01:19

    Below worked for me.

    let array = [
        { id: 1, value: "itemname" },
        { id: 2, value: "itemname" }
    ];
    
    let item1 = array.find(i => i.id === 1);
    
    0 讨论(0)
  • 2020-12-29 01:27

    Use Array.find:

    let array = [
        { id: 1, value: "itemname" },
        { id: 2, value: "itemname" }
    ];
    
    let item1 = array.find(i => i.id === 1);
    

    Array.find at MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题