is there a function in lodash to replace matched item

前端 未结 15 2281
孤街浪徒
孤街浪徒 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:05

    In your case all you need to do is to find object in array and use Array.prototype.splice() method, read more details here:

    var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
    
    // Find item index using _.findIndex (thanks @AJ Richardson for comment)
    var index = _.findIndex(arr, {id: 1});
    
    // Replace item at index using native splice
    arr.splice(index, 1, {id: 100, name: 'New object.'});
    
    // "console.log" result
    document.write(JSON.stringify( arr ));

提交回复
热议问题