is there a function in lodash to replace matched item

前端 未结 15 2337
孤街浪徒
孤街浪徒 2020-12-07 13:42

I wonder if there is a simpler method in lodash to replace an item in a JavaScript collection? (Possible duplicate but I did not understand the answer there:)

I look

15条回答
  •  余生分开走
    2020-12-07 14:03

    Using lodash unionWith function, you can accomplish a simple upsert to an object. The documentation states that if there is a match, it will use the first array. Wrap your updated object in [ ] (array) and put it as the first array of the union function. Simply specify your matching logic and if found it will replace it and if not it will add it

    Example:

    let contacts = [
         {type: 'email', desc: 'work', primary: true, value: 'email prim'}, 
         {type: 'phone', desc: 'cell', primary: true, value:'phone prim'},
         {type: 'phone', desc: 'cell', primary: false,value:'phone secondary'},
         {type: 'email', desc: 'cell', primary: false,value:'email secondary'}
    ]
    
    // Update contacts because found a match
    _.unionWith([{type: 'email', desc: 'work', primary: true, value: 'email updated'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)
    
    // Add to contacts - no match found
    _.unionWith([{type: 'fax', desc: 'work', primary: true, value: 'fax added'}], contacts, (l, r) => l.type == r.type && l.primary == r.primary)
    

提交回复
热议问题