DEV Community

Duc Nguyen Van
Duc Nguyen Van

Posted on

I'm having trouble merging arrays in reactjs

i'm doing a recursive array merge into an array but it's not working

this is current data

let currentData = [
   {
     "id":1,
     "content":"Comment 1"
     "answers":[
       {
       "id":3,
       "content":"Comment 3"
       "answers":[ 
         {
         "id":4,
         "content":"Comment 4",
         "answers":[]
         },
         {
         "id":5,
         "content":"Comment 5",
         "answers":[]
         }]
       }
     ]
   }
   {
     "id":2,
     "contents":"Comment 2"
     "answers":[
       {
          "id"6,
          "content":"Comment 6",
          "answers":[]
       }
     ]
   }
 ]
Enter fullscreen mode Exit fullscreen mode

I want like this

[
     {
          "id": 1,
          "content": "Comment 1"
     },
     {
          "id": 2,
          "content": "comment 2"
     },
     {
          "id:": 3,
          "content": "comment 3"
     },...
]
Enter fullscreen mode Exit fullscreen mode

I tried using this function but it doesn't work

 const [replyList, setReplyList] = useState([])
 useEffect(()=>{
    handleMerge(currentData)
  },[])
 const handleMerge = (reply) => {
    if (reply.length == 0) {
      return
   }
    for (let i = 0; i < reply.length; i++) {
        setReplyList([...replyList,reply[i]])
        handleMerge(reply[i].reply)
      }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
_bkeren profile image
'' • Edited

do not use setReplyList in a loop, because it is async, it's not guaranteed to change its data immediately.

write a method that takes an array like the first one and returns the desired array, and then setReplyList(result)

Another option maybe useMemo. You can use useMemo that depends on the first array structure and then returns the second one