0

I am currently working on a project with NextJs, however in between i am syncing the live data with static one to keep it updated. But idk why these set of lines shows un-expected behaviour, let's take a look!

  • I am using memcache npm package for storing live data in-memory

Code


const catagories = ["coding", "gaming", "tricks"];
console.log("Before::", cache.get("gaming"));
// cache.get("gaming") => [{id: 1, likes: ['dev', 'lorem', 'ed'], dislikes: ['ram']}, {id: 2, likes: ['john', 'joe'], dislikes: ['loe', 'kun']}]

let result = {};

catagories.map((catagory) => {

        result[catagory] = cache.get(catagory) || [];

})

// From now on we not even mention cache.get(catagory), BUT Still its changing because result[catagory] changes...

let username = req.body.username; // diana

for(const catagory in result){
                    
    if(result[catagory] && result[catagory].length){

                
           result[catagory].map((spack_live_data, idx) =>{

    
                   spack_live_data.is_liked = spack_live_data.likes.includes(username)
                   spack_live_data.is_disliked = spack_live_data.dislikes.includes(username)
    
                   spack_live_data.likes = spack_live_data.likes.length
                   spack_live_data.dislikes = spack_live_data.dislikes.length

    
            })
                
    }

}

console.log("After::", cache.get("gaming"));
// cache.get("gaming") => [{id: 1, likes: 3, is_liked: false, dislikes: 1, is_disliked: false}, {id: 2, likes: 2, is_liked: false, dislikes: 2, is_disliked: false}]

From above code i have no idea why even cache's data is affecting even i am changing the result's data

I try replacing the map function with basic for loop/index based , but still the same issue.

I just want to change the result but don't want to change the cache dict/object

  • You're setting `result[catagory]` to `cache.get(catagory)`, and modifying one variable modifies the other, because both variables point to the same object value. This is a duplicate of [What is the difference between a deep copy and a shallow copy?](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy) – Andy Ray Dec 04 '22 at 08:25
  • @AndyRay Thanks Mate, any way to get rid of this behaviour? – Malloc Calloc Dec 04 '22 at 08:29

0 Answers0