Skip to content
Advertisement

How to find an element by id in nested arrays

i trying create reply to comments in my project, and I have some problems with adding comments to reducer, i am trying to add an reply without reloading the page.

My comments looks at:

[
  id:
  createdAt:
  text:
  comments: [
              id:
              createdAt:
              text:
              comments: [
                          id:
                          createdAt:
                          text:
                          comments: [],

                          id:
                          createdAt:
                          text:
                          comments: []
              ]

]

It’s my reducer, now i trying write to console:

[sendReplyRoutine.SUCCESS]: (state, action) => {
    state.reply = initialState.reply;

    function findById(arr, id, nestingKey) {
      return arr.find(d => d.id === id)
        || findById(arr.flatMap(d => d[nestingKey] || []), id, 'comments')
        || 'Not found';
    }

    console.log(findById(state.post.comments, state.reply.replyCommentId, 'comments'));
  }

I can’t think of how I can iterate through my array to add a comment to the block I need.

For example this is how i add the usual comment:

[sendCommentRoutine.SUCCESS]: (state, action) => {
    state.comment = initialState.comment;
    console.log(action.payload);
    state.post.comments.unshift(action.payload);
  }

Advertisement

Answer

If I understood your problem correctly, that might be helpful.

const comments = [
  {
    id: 1,
    createdAt: '',
    text: '',
    comments: [
      {
        id: 2,
        comments: [
          {
            id: 6,
            comments: []
          }
        ],
      },
      {
        id: 3,
        comments: [
          {
            id: 4,
            comments: []
          },
          {
            id: 5,
            commensts: []
          }
        ]
      }
    ],
  },
  {
    id: 7,
    comments: []
  }
];

const findById = (id, comments, idx = 0) => {
  const item = comments[idx];
  
  if (!item) return null;
  if (item.id === id) return item;

  const newComments = item.comments.length ? [...comments, ...item.comments] : comments;

  return findById(id, newComments, idx + 1);
};

console.log(findById(5, comments));
console.log(findById(7, comments));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement