How to replace an object in object array in javascript (lodash)

▼魔方 西西 提交于 2019-12-05 14:13:17
stasovlas

you can do it with _.unionBy

var res = _.unionBy([obj], arr, 'id');

but check a note at this comment

You can use .findIndex()

var i = arr.findIndex(o => o.id === obj.id);
if (arr[i]) { arr[i] = obj } else { arr.push(obj) };

You can use _.findIndex with the _.matchesProperty shorthand:

var index = _.findIndex(arr, ['id', obj.id]);
arr[index >= 0 ? index : arr.length] = obj;

var arr = [{
  id: "a1",
  guid: "sdfsfd",
  value: "abc",
  status: false
}, {
  id: "a2",
  guid: "sdfsfd",
  value: "def",
  status: true
}];

var obj = {
  id      : "a1",
  guid    : "sdfsfd",
  value   : "xyz",
  status  :  true
};

var index = _.findIndex(arr, ['id', obj.id]);
arr[index >= 0 ? index : arr.length] = obj;
                        
console.log(arr);
.as-console-wrapper { min-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Here's a lodash solution that uses keyBy to create an object wherein each item in the collection is represented by their id, set to override the new object or possibly add the new object and lastly values to get the array representation of the object.

var result = _(arr).keyBy('id').set(obj.id, obj).values().value();

var arr = [
  {
    id    : "a1",
    guid  : "sdfsfd",
    value : "abc",
    status: false
  },
  {
    id    : "a2",
    guid  : "sdfsfd",
    value : "def",
    status: true
  }
];

var obj = {
  id      : "a1",
  guid    : "sdfsfd",
  value   : "xyz",
  status  :  true
}

var result = _(arr).keyBy('id').set(obj.id, obj).values().value();

console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

you can loop and use 'splice' function:

var added = false;
for(var i=0;i<arr.length; i++){
   if(arr[i].id === obj.id){
        arr.splice(i,1,obj);
        added = true;
        break;
   }
}

if(!added) arr.push(obj);

EDIT: missed added condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!