There is an array:

var list = [{ status:0, id:1, img:"/assets/images/user-avatar-cropped.png", value:110, result:1 },{ status:0, id:2, img:"/assets/images/user-avatar-cropped.png", value:120, result:1 }, { status:0, id:3, img:"/assets/images/user-avatar-cropped.png", value:130, result:1 }, { status:0, id:4, img:"/assets/images/user-avatar-cropped.png", value:140, result:1 },] 

The array needs to be updated, for example. You need to change the object in which the value id = 1, and set it to status = 2, and result = 0.

I understand about logic that you first need to remove this object from the array, and then re-start with new (necessary) values.

  1. How to remove an object from an array with a corresponding id (for example, delete an object where id = 1)?
  2. Is it possible to somehow simply update an object (without deleting it and then adding it). Well, or is there any other solutions to this problem.

    3 answers 3

    Cycle through the array, find the element with the desired id in it and replace the status, you can

     changeDesc = (id, status, result) => { let item = list.find(x => x.id === id); item.status = status; item.result = result; }; changeDesc( 1, 2, 0); console.log(list); 

    In this case, the item is not deleted, as you expected, but it changes its value.

    To remove an element from an array, you can use the array.splice(index, 1); :

     function removeElement( id) { for (let i in list) { if (list[i].id == id) { list.splice(i, 1); break; } } }; 

      Delete does not need anything. It is enough to refer to the field and replace:

       list[0].id = 666; list[0].status = 1; 

      But how will you look for the field - is another question. For example, in a loop, run through the array and search for an object with the desired id or something else

       list.forEach(function (element) { if (element.id == 1) { element.id = 666; element.status = 1; } }); 
      • I just need an example of how to find an object with the id I need - stoner
      • @kiLLro do not see this in the question. Как удалить объект из массива с соответствующим id? and Можно ли как-то просто обновить объект (без его удаления и последующего добавления). ...... but added an example - Alexey Shimansky

      Find an object using the find() method:

       var found = list.find((obj) => { return obj.id === 1; }); 

      Change the required properties with a simple override:

       found.status = 2; found.result = 0; 

      But ideally, you should first check whether the element is found:

       if (found) { found.status = 2; found.result = 0; } 

      If several elements can be found one by one id , then use the filter() method:

       var foundArr = list.filter((obj) => { return obj.id === 1; }); 

      And change the value cyclically:

       foundArr.forEach((found) => { found.status = 2; found.result = 0; });