0

I am stuck with a real stupid problem. I trying to use D3.js to plot data(some scores of people) dynamically.

  1. I get the record data from a firebase database whenever a change is happening. Here I mimic this with a object with some static score data in it
  2. I add a time key/value pair in the record
  3. then I want to prepare the data for D3 by creating an array called data on which I add the record every second. I use the array push method and pass in the record with data.push(record)
  4. I put the record object onto the console which is nicely doing what intended. 5.tit but the value of time console.logged with the for loop is showing for all elements, also the past ones, the current time value (tahre than 0, 1, 2, 3, 4,.....)

I am stuck since 3 hours, believe or not.

If somebody can help me. Thanks

 var data = [];
  record = {Fanny : 40, Joe : 20};
  var time = 0;

  record["time"] = time;

  console.log(record);


  myTimer = setInterval(function () {


    time = time + 1;

    record.time = time; 

    console.log(record);

    data.push(record);


    for (i = 0; i < data.length; i++) { 
          console.log(data[i].time)

    }
  },1000);
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Peter HIRT
  • 741
  • 2
  • 8
  • 18

2 Answers2

2

You need to make a new record for every iteration.

Right now, you have just the same single (but repeated many times in the array) record and keep updating it.

data.push({ Fanny: 40, Joe: 20, time: time });
Thilo
  • 257,207
  • 101
  • 511
  • 656
  • so, what you say is that I actually store the object, not the content of the object. Any way to store the content of the object? – Peter HIRT Sep 29 '14 at 01:45
  • You'd need to copy it somehow. Look at this thread: http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object?rq=1 – Thilo Sep 29 '14 at 01:58
0

You may be dealing with a referencing issue, meaning that say

a is an object

a.name = 'toto';
var b = a;
b.name = 'titi';

console.log(a.name) // will output 'titi'

One way to work around that is to do the not so pretty

var b = JSON.parse(JSON.stringify(a));

to break the referencing

Moustachiste
  • 412
  • 4
  • 14