There is initially such a construction

{ books: [ { id: '200', author: '4124', name: '412', imgUrl: 'data:image/jpeg;base64' } ] } 

We need to somehow go through the array of objects in the books property, and replace the object in the array with the one that passes by id , and then return the new object with the books property in which we replaced the object without changing the old object.

Those. the total should return a new object

 { books: [ { id: '200', author: 'new author', name: 'new name', imgUrl: 'some img' } ] } 

We return a new object with the books property, but I don’t know how to replace the object and add to the array.

 const changedItem = action.book return Object.assign({}, state, { books: state.books.map(item => item.id === changedItem.id ? changedItem : item) }); 
  • Learn how to bypass object properties and array elements. for ... in and forEach respectively and do a brute force. Here properties do not need to iterate, only the elements of the array. - Dmitriy
  • @ Dmitriy and I get objects in the books array using a map .... - Drop

2 answers 2

If I understand you correctly, it should look like this:

  var object = { books: [ { id: '200', author: '4124', name: '412', imgUrl: 'data:image/jpeg;base64' } ] }; function replace(object, searchID){ var replacedObject = object; for(var i = 0;i<replacedObject.books.length;i++){ if(replacedObject.books[i].id != searchID) continue; replacedObject.books[i].author = 'newAuthor'; return replacedObject; } } alert(replace(object, 200).books[0].author); 

the old object does not change, and the new one can be entered into a variable by calling a function instead of 4124 instead of me - newAuthor

     Object.books.forEach(function(item, i, arr) { if(item.id == "200") { Object.books[i] = {id: "200", ...} // Новый объект с новыми свойствами // Или так Object.books[i].author = "..."; и так для каждого изменяемого свойства } }) 
    • Object cannot be iterated, it is a constructor. In my example, it is used to create a new object and copy into it all the properties of the old state object in which the books property is located without changing the old object and creating a new one. This is of course my mistake that I didn’t add on не изменяя старый объект . - Drop