2

How do I turn this array with keys

> dd
[ 'DeviceName',
  'counter1',
  'counter2',
  'counter3',
  'counter4' ]

into this object array with objects

[
    { data: 'DeviceName' },
    { data: 'counter1' },
    { data: 'counter2' },
    { data: 'counter3' },
    { data: 'counter4' }
]

I have tried this function, but the problem is that the data key is the same in them all.

Is there a way around this?

 newdd=function toObject(arr) {
      var rv = {};
      var a =[];
        for (var i = 0; i < arr.length; ++i) {
        rv["data"] = arr[i];
        a.push(rv);
        }
      return a;
    }

This gives me:

> newdd(dd)
[ { data: 'counter4' },
  { data: 'counter4' },
  { data: 'counter4' },
  { data: 'counter4' },
  { data: 'counter4' } ]
johnnyRose
  • 7,310
  • 17
  • 40
  • 61
HattrickNZ
  • 4,373
  • 15
  • 54
  • 98
  • 2
    think [this](http://stackoverflow.com/questions/22280580/turning-an-array-into-an-array-of-objects-with-underscore-js) might be what I want – HattrickNZ Sep 03 '15 at 00:14

3 Answers3

5

Array.prototype.map():

dd.map(function(element)
{
    return { data: element };
});
Siguza
  • 21,155
  • 6
  • 52
  • 89
4

That's because objects in JavaScript are passed by reference (or really call by sharing), not by value, so you're always referencing the same object.

Just move your assignment for rv = {} inside your for loop and it should fix your problem. Reassigning rv to a new object as opposed to modifying the existing instance will result in the desired behavior.

newdd = function toObject(arr) {
    var a =[];
    for (var i = 0; i < arr.length; ++i) {
        var rv = {};
        rv["data"] = arr[i];
        a.push(rv);
    }

    return a;
 }

See Working with objects on the Mozilla Developer Network to help build your understanding of objects.

Community
  • 1
  • 1
johnnyRose
  • 7,310
  • 17
  • 40
  • 61
2

Try this instead:

function toObject(arr) {
    var a =[];
    for (var i = 0; i < arr.length; ++i) {
        a.push({ data: arr[i] });
    }
    return a;
}
Andy
  • 61,948
  • 13
  • 68
  • 95