is there a function in lodash to replace matched item

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

    You can do it without using lodash.

    let arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
    let newObj = {id: 1, name: "new Person"}
    
    /*Add new prototype function on Array class*/
    Array.prototype._replaceObj = function(newObj, key) {
      return this.map(obj => (obj[key] === newObj[key] ? newObj : obj));
    };
    
    /*return [{id: 1, name: "new Person"}, {id: 2, name: "Person 2"}]*/
    arr._replaceObj(newObj, "id") 
    

提交回复
热议问题