S
S
Shiva62019-10-30 00:17:48
JavaScript
Shiva6, 2019-10-30 00:17:48

How to iterate over an array of objects and change a property inside the desired object, which also represents an array of objects?

I have the following state structure:

{
  articles: [
    {
      id: '1AAAA',
      title: 'AAAA',
      summary: 'minimalAAA',
      text: 'dsffsfsegrsgsrgsrs',
      comments: [
        { id: '4cdrbdrbvoido',
          name: 'Den',
          comment: 'Ljbelkfei nfien nfien  nfien nfien nfien nfien nfien nfien'},

        {id: '5vjdbnvsjm;slv',
          name: 'Ben',
          comment: 'Ljbelkfei nfien nfien  nfien nfien nfien nfien nfien nfien' }
      ]
    },

    {
      id: '2BBBBB',
      title: 'BBBBB',
      summary: 'minimalBBB',
      text: 'dsffsfsegrsgsrgsrs',
      comments: [
        { id: '1cudohvoido',
          name: 'Sem',
          comment: 'Hnefei nfien nfien  nfien nfien nfien nfien nfien nfien'},

        {id: '2knsdknvpdo',
          name: 'Pen',
          comment: 'Hnefei nfien nfien  nfien nfien nfien nfien nfien nfien'}
      ]
    }
  ]
};

Each object inside articles is an article with its own unique id and other data, including comments to the article inside comments, which are also in the array.
I created an action that in the reducer passes only the id of the comment that needs to be removed from the state from the variables.
const commentDelete = (idComment) => {
  return {
    type: 'COMMENT_DELETE',
    id:idComment,
  };
};

I don’t know how to correctly write a function that will return a new state but without a deleted comment. It won’t work through the standard state.articles.filter() method, you may need to add a condition or a cycle inside the filter method, but I still haven’t found a solution.
I even thought of somehow changing the state structure so as not to go so deep inside the object, but I don’t want to rewrite the rest of the actions.
For example, this is how I did the deletion of the article
case 'ARTICLES_DELETE':
      const delArt = state.articles.filter(user => (user.id !== action.id));
      return {
        ...state,
        articles: [ ...delArt]
      };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stockholm Syndrome, 2019-10-30
@Shiva6

return {
  ...state,
  articles: state.articles.map(({comments, ...o}) => ({
    ...o, 
    comments: comments.filter((c) => c.id !== action.id)
  }))
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question