最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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))
    }
发布评论

评论列表(0)

  1. 暂无评论