F
F
fierfoxik2017-07-15 18:15:56
JavaScript
fierfoxik, 2017-07-15 18:15:56

How to replace data in an array object and return a new array object?

Good time!
there is such a data structure

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

the books property with an array of objects is created like this
Object.assign({}, state, {
                books: [
                    ...state.books,
                    action.book
                ]

We need to somehow go through the array of objects in the books property and replace the object with the one that passes by id and then return a new object with the books property in which we replaced the object.
i.e. the result 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 it to the array.
const changedItem = action.book
Object.assign({}, state, {
                books: state.books.map(item => item.id === changedItem.id ? changedItem : item)
            });

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Ernest Fayzullin, 2017-07-16
@ernesto77

How to replace data in an array object and return a new array object?

action.book.map = function (book) {
    book.imgUrl = '/img/example.jpg'

    return book
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question