is there a function in lodash to replace matched item

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

    Came across this as well and did it simply that way.

    const persons = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
    const updatedPerson = {id: 1, name: "new Person Name"}
    const updatedPersons = persons.map(person => (
      person.id === updated.id
        ? updatedPerson
        : person
    ))
    

    If wanted we can generalize it

    const replaceWhere = (list, predicate, replacement) => {
      return list.map(item => predicate(item) ? replacement : item)
    }
    
    replaceWhere(persons, person => person.id === updatedPerson.id, updatedPerson)
    

提交回复
热议问题