0

I have small issue, I want merge Object and array by map function. My code is:

var headers = [{
    "name": "Date",
    "dtype": "date",
    "dtitle": "Inserta date"
  }, {
    "name": "Patient",
    "dtype": "text",
    "dtitle": "Insert patient name"
  }

];


var rows = [
  [1, 2],
  [3, 4],
  [5, 6]
];

var c = 0;
var item = [];
var items = [];
rows.map(function(v) {

  v.map(function(a) {
    h = headers[c];
    h.value = a;
    item.push(h);
    c++;
  });
  items.push(item);
  c = 0;
});
console.log(items);

Finally I get always duplicate last record from rows array. I don't know where I made a mistake. I try use _ each and for loop but I get always the same result.

I want receive this result ex:

result = [
  [
    {
        "name":"Date",
        "dtype":"date",
        "dtitle":"Inserta date",
  "value":1
    },
    {
        "name":"Patient",
        "dtype":"text",
        "dtitle":"Insert patient name",
  "value":2
    }

],

  [
    {
        "name":"Date",
        "dtype":"date",
        "dtitle":"Inserta date",
  "value":3
    },
    {
        "name":"Patient",
        "dtype":"text",
        "dtitle":"Insert patient name",
  "value":4
    }

]];
kogutu
  • 35
  • 2
  • 8

1 Answers1

0

h = headers[c]; will give you the reference to one of the objects in your headers array. You change it, and put the reference into the result; you change it again, and put another reference to it. All of the Date objects are actually the same object (you can verify that headers now also contains value: 5 in the Date object). Same for the Patient object.

Instead of taking a reference, you need to clone the object - something like h = clone(headers[c]);.

Community
  • 1
  • 1
Amadan
  • 191,408
  • 23
  • 240
  • 301