How do I use the includes method in lodash to check if an object is in the collection?

前端 未结 3 1237
一整个雨季
一整个雨季 2020-12-23 20:03

lodash lets me check for membership of basic data types with includes:

_.includes([1, 2, 3], 2)
> true

But the following do

3条回答
  •  别那么骄傲
    2020-12-23 20:38

    Supplementing the answer by p.s.w.g, here are three other ways of achieving this using lodash 4.17.5, without using _.includes():

    Say you want to add object entry to an array of objects numbers, only if entry does not exist already.

    let numbers = [
        { to: 1, from: 2 },
        { to: 3, from: 4 },
        { to: 5, from: 6 },
        { to: 7, from: 8 },
        { to: 1, from: 2 } // intentionally added duplicate
    ];
    
    let entry = { to: 1, from: 2 };
    
    /* 
     * 1. This will return the *index of the first* element that matches:
     */
    _.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
    // output: 0
    
    
    /* 
     * 2. This will return the entry that matches. Even if the entry exists
     *    multiple time, it is only returned once.
     */
    _.find(numbers, (o) => { return _.isMatch(o, entry) });
    // output: {to: 1, from: 2}
    
    
    /* 
     * 3. This will return an array of objects containing all the matches.
     *    If an entry exists multiple times, if is returned multiple times.
     */
    _.filter(numbers, _.matches(entry));
    // output: [{to: 1, from: 2}, {to: 1, from: 2}]
    

    If you want to return a Boolean, in the first case, you can check the index that is being returned:

    _.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
    // output: true
    

提交回复
热议问题