javascript - Array.Push overwrites the previous Value Node Js - Stack Overflow

Good day.I have an global array and it MUST be global.var ments= [];I have an callback of a socket whe

Good day. I have an global array and it MUST be global.

var ments= [];

I have an callback of a socket where i am iterating through it and adding the values.

Better with the code :

    socket.on('mentAdded', function (data) {
    if (data !== null) {
        var stringify = JSON.stringify(data);
        var json = JSON.parse(stringify);

        Object.keys(users).forEach(function (key) {
            if (key !== "null") {
                data.eachUserId = key;
                console.log("data added with id " + key + " the size of ments is " + ments.size);
                ments.push(data);
            }
        });
        console.log("ment was added");
    }

    socket.broadcast.emit('onCommentAdded', data);
});

Here my console.Log("data added with id)... is printing everything correctly and ideally i want to add a new value to the existing data which is a json data and the name of a new value is eachUserId which value must be fully different as i am doing it inside the loop as you can see.

And here is how i get the items afterwards.

   for (var f = 0; f < Object.keys(ments).length; f++) {
        var ment = ments[f];
        var eachUserId = ment.eachUserId;
        console.log("checking with current user id" + userId + " each user id" + eachUserId + " or each user id in [] way " + ment['eachUserId']);
        if (eachUserId === userId) {
            socket.emit('onCommentAdded', ment);
        }
    }

Here the eachUserId is always the very last item which was added in loop... what am i doing wrong? Why the push() method overwrite every value?

Good day. I have an global array and it MUST be global.

var ments= [];

I have an callback of a socket where i am iterating through it and adding the values.

Better with the code :

    socket.on('mentAdded', function (data) {
    if (data !== null) {
        var stringify = JSON.stringify(data);
        var json = JSON.parse(stringify);

        Object.keys(users).forEach(function (key) {
            if (key !== "null") {
                data.eachUserId = key;
                console.log("data added with id " + key + " the size of ments is " + ments.size);
                ments.push(data);
            }
        });
        console.log("ment was added");
    }

    socket.broadcast.emit('onCommentAdded', data);
});

Here my console.Log("data added with id)... is printing everything correctly and ideally i want to add a new value to the existing data which is a json data and the name of a new value is eachUserId which value must be fully different as i am doing it inside the loop as you can see.

And here is how i get the items afterwards.

   for (var f = 0; f < Object.keys(ments).length; f++) {
        var ment = ments[f];
        var eachUserId = ment.eachUserId;
        console.log("checking with current user id" + userId + " each user id" + eachUserId + " or each user id in [] way " + ment['eachUserId']);
        if (eachUserId === userId) {
            socket.emit('onCommentAdded', ment);
        }
    }

Here the eachUserId is always the very last item which was added in loop... what am i doing wrong? Why the push() method overwrite every value?

Share Improve this question asked Apr 14, 2017 at 10:36 Volo AppsVolo Apps 2351 gold badge3 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Problem:

You problem is when you assign the value to eachUserId to object data. You have only 1 object named data and you are adding this same object into the array over and over again. But remember they all refer to the same object, and when you'll change anything in that object it'll reflect everywhere.

So, when you change data.eachUserId = key; in loop, it changes for all items in array. And at the end all of them contains the last eachUserId value you assigned to it.

Solution:

You need to clone the object, and then push it into the array.


I will suggest you to use lodash library and cloneDeep method to create a deep clone of your object.

var _ = require('lodash');  //require "lodash"

socket.on('mentAdded', function (data) {
    if (data !== null) {        
        Object.keys(users).forEach(function (key) {
            if (key !== "null") {
                var dataClone = _.cloneDeep(data);  //create deep clone
                dataClone.eachUserId = key;         //assign "key"
                ments.push(dataClone);           //push into the array
            }
        });
        console.log("ment was added");
    }    
    socket.broadcast.emit('onCommentAdded', data);
});

Use Spread Operator, it is already Stage 4 (ECMAScript)

const foo = {}

const bar = {...foo}

foo.a = 1;
bar.a = 10;

console.log(foo) // {a : 1}
console.log(bar) // {a : 10}

Are you sure your ments is containing the required data. Wrap it inside a closure, so it creates a new scope for each iteration and passes the right data.

for (var f = 0; f < Object.keys(ments).length; f++) {
       (function(f){
          var ment = ments[f];
          var eachUserId = ment.eachUserId;
          console.log("checking with current user id" + userId + " each user id" + eachUserId + " or each user id in [] way " + ment['eachUserId']);
          if (eachUserId === userId) {
             socket.emit('onCommentAdded', ment);
          }
       )(f))
    }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744630250a4584814.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信