TypeScript - Take object out of array based on attribute value

后端 未结 5 1817
名媛妹妹
名媛妹妹 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)

提交回复
热议问题