0

I currently have an array of objects called posts.

for(var i = 0; i < posts.length; i++){
      let post = posts[i]
      let { item, category } = post
      let postCollections = categories[category]
      for(var col in userCollections[category]){
        let items = userCollections[category][col].items
        if(items && col){
          postCollections[col]['item'] = item
          console.log("HERE!, item)
          if(item in items){
            postCollections[col]['joined'] = true
          }else{
            postCollections[col]['joined'] = false
          }
        }
      }
      posts[i]['collections'] = postCollections
    }

When this is run, the print out for "HERE!" shows the item value is unique. When I print out posts and look at the value for key items they all show the same item.

Matthew Barbara
  • 3,792
  • 2
  • 21
  • 32
Thingamajig
  • 4,107
  • 7
  • 33
  • 61

1 Answers1

0

This was a tough solve. Turns out the line where I set postCollections was using the same object over and over again. Copying the object like this has done the trick:

let postCollections = JSON.parse(JSON.stringify(categories[category]));
Thingamajig
  • 4,107
  • 7
  • 33
  • 61
  • if `categories[category]` is one level deep object or array, then you can use `...` spread syntax or slice also ( slice is only present for array ). Reason for this problem is since object's are references so when you update any of the element it is noticeable at all other element because they all referring to the same memory location – Code Maniac Sep 14 '19 at 03:03