Home > Software engineering >  updating array of object properties using for of loop in js
updating array of object properties using for of loop in js

Time:11-23

 for(let post of posts){
        console.log("post",post.photoDetails)
        if(post['photoDetails']?.imageName){
            console.log(post.photoDetails === posts[0].photoDetails,"check equality") // true
            const getObjectParams = {
                Bucket: process.env.AWS_BUCKET_NAME,
                Key: post.photoDetails.imageName
            }
            const command = new GetObjectCommand(getObjectParams);
            const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });
            post["photoDetails"]["url"] = url
            // spread operator not working 
            // post["photoDetails"] = {
            //     ...post.photoDetails,
            //     url:url
            // }
            // replace complete post 
             post = {
                ...post,
                url:url
             }
            console.log(post)
        }
    }
 return res.status(200).json({
    'message': 'user Profile Details ',
    'posts' : posts
}) 

i am having following doubts

  1. post["photoDetails"]["url"] = url here photoDetails is my object ,I am trying to add key and value using bracket notation.Why it is not working?

let a = { "name": "dd" }

a["sec"] = 3

// a // a is having both name and sec but why in my case key is not getting added

  1. Next i tried to assign a new object to photoDetails using spread operator .still my post is not updated i don't know why

  2. I am unable to add to photoDetails so i tried to add a new key to my post and send.

    post = {...post,url:url} . Now inside for loop my log is showing as expected added an url key but in response (where i am sending posts using res object) we are getting old posts(non updated posts) .According my knowledge objects are reference types .If we change the reference any where it should effect the original .But why in my case post = {...post,url:url} the original posts is not getting effected even i updated post

  3. Finally how to add url key to my photoDetails Object and send in response

my posts object

let posts =  [{
    _id: "637d1016223653199f35a482",
    password: '$2b$10$s9dJHy/hcvnAoNZWryiGj.j3cMGYFwTerhS6JqhmQRj5ZlBUeQ/PW',
    gender: 0,
    __v: 0,
    profileDetails: {
      _id: "637d103b223653199f35a488",
      profileDetails: "637d1016223653199f35a482",
      __v: 0
    },
    familyDetails: {
      _id: "637d1083223653199f35a48e",
      fatherName: 'opll',
      fatheroccupation: 'farmer'
    },
    photoDetails: {
      imageName: '1669140955730signin_image.jpg',
      userId: '637d1016223653199f35a482',
      __v: 0
    }
  }

CodePudding user response:

Let's simplify your code a bit:

const posts = [{ }, { }];

console.log('log 1', posts);

for (let post of posts) {
  post["url"] = 'foo';

  post = {
    ...post,
    url: 'bar'
  }

  console.log('log 2', post);
}

console.log('log 3', posts);
.as-console-wrapper { max-height: 100% !important; }

Now you can see that post["details"]["url"] = 'foo'; actually works like you'd expect. In the final console log, you'll see 'foo' returned.

So why doesn't it show 'bar'?

Your post = { ... stuff ... } doesn't update the value in the array.
post is a reference to an object. It doesn't know about that array.

An array is nothing but a list of pointers to said objects:

const posts = [pointsToObjectFoo, pointsToObjectBar]

If you then iterate over said array, your object variable post is a copy of the pointer:

for (let post of posts) {
// `post`'s value is _also_ a pointer to objectFoo.

Now, when you assign a new object to post, you're replacing the pointer that's stored in post:

post = {} // objectBar
// post now points to objectBar

The array doesn't know that you updated that pointer somewhere else. Why should it?

  • Related