0

For example I have this following object.

var arr = [
     {id:1,name:"arjun"},
     {id:2,name:"kishore"}
]

When I push an object to an above Array, something like this

arr.push({id:1,name:"akash"})

It should update the object.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Arjun Sarthi
  • 109
  • 1
  • 11
  • You might consider using an actual object indexed by ID instead, then it's very simple to assign to `obj[id] = 'somename'` (otherwise you'll have to use something like `.find`) – CertainPerformance Jun 25 '18 at 09:59
  • Then you will have to overload the `.push` method to update existing objects instead of just appending to the array as it does by default. `arr.push = function (obj) { /* write code here */ }` – deceze Jun 25 '18 at 10:02
  • may be you might use an object instead of an array like this. [https://stackoverflow.com/questions/25764719/update-if-exists-or-add-new-element-to-array-of-objects-elegant-way-in-javascr](https://stackoverflow.com/questions/25764719/update-if-exists-or-add-new-element-to-array-of-objects-elegant-way-in-javascr) – Priefy Jun 25 '18 at 10:03
  • But overriding `push` is not a good idea if you are doing `push` for multiple/simple/other arrays and for multiple purposes – Muhammad Usman Jun 25 '18 at 10:04
  • @Arjun I added answer. Hope it will work as per your expectations. – Debug Diva Jun 25 '18 at 10:20
  • 1
    Possible duplicate of [Update if exists or add new element to array of objects - elegant way in javascript + lodash](https://stackoverflow.com/questions/25764719/update-if-exists-or-add-new-element-to-array-of-objects-elegant-way-in-javascr) – Jack jdeoel Jun 25 '18 at 10:21

2 Answers2

1

var arr = [{id:1,name:"arjun"},{id:2,name:"kishore"}];
arr.push = function(data){
    for(let i=0;i<this.length;i++){
      if(data.id == this[i].id){
          this[i].name = data.name;
          return this.length;
      }
    }
    this.push(data);
  return this.length;
}
arr.push({id:1,name:"akash"});
console.log(arr);
Akhil Aravind
  • 5,741
  • 16
  • 35
Onk_r
  • 836
  • 4
  • 21
0

Try this to update the object property of an array :

var arr = [{id:1,name:"arjun"},{id:2,name:"kishore"}];

var obj = {id:1,name:"akash"};

arr.map(item => {
    (item.id == obj.id) ? (item.name = obj.name) : ''; 
});


console.log("Modified Array", arr);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • Rohit, I tried your solution but it doesnt work as expected. Ok, let me elaborate the problem a little bit. I have a table having more than 30 pages, each page having 10 rows, Each row having one column that has a dropdown. I should be able to submit multiple request when i change dropdown values for each row, ON onchange event I am passing a data, and I am converting that into a json. And trying to push it. In short, Your code only works when there are two objects in an array, not more than that. – Arjun Sarthi Jun 26 '18 at 07:31
  • @ArjunSarthi I did not get you – Debug Diva Jun 26 '18 at 08:44