is there a function in lodash to replace matched item

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

    Not bad variant too)

    var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
    
    var id = 1; //id to find
    
    arr[_.find(arr, {id: id})].name = 'New Person';
    
    0 讨论(0)
  • 2020-12-07 14:10
    var arr= [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
    var index = _.findIndex(arr, {id: 1});
    arr[index] = {id: 100, name: 'xyz'}
    
    0 讨论(0)
  • 2020-12-07 14:14

    Seems like the simplest solution would to use ES6's .map or lodash's _.map:

    var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
    
    // lodash
    var newArr = _.map(arr, function(a) {
      return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
    });
    
    // ES6
    var newArr = arr.map(function(a) {
      return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
    });
    

    This has the nice effect of avoiding mutating the original array.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-07 14:18

    You can also use findIndex and pick to achieve the same result:

      var arr  = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
      var data = {id: 2, name: 'Person 2 (updated)'};
      var index = _.findIndex(arr, _.pick(data, 'id'));
      if( index !== -1) {
        arr.splice(index, 1, data);
      } else {
        arr.push(data);
      }
    
    0 讨论(0)
  • 2020-12-07 14:19

    If you're looking for a way to immutably change the collection (as I was when I found your question), you might take a look at immutability-helper, a library forked from the original React util. In your case, you would accomplish what you mentioned via the following:

    var update = require('immutability-helper')
    var arr = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}]
    var newArray = update(arr, { 0: { name: { $set: 'New Name' } } })
    //=> [{id: 1, name: "New Name"}, {id:2, name:"Person 2"}]
    
    0 讨论(0)
提交回复
热议问题