HattrickNZ
HattrickNZ

Reputation: 4643

Turning an array into an array of objects

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' } ]

Upvotes: 2

Views: 80

Answers (3)

Andy
Andy

Reputation: 63514

Try this instead:

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

Upvotes: 2

johnnyRose
johnnyRose

Reputation: 7490

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.

Upvotes: 4

Siguza
Siguza

Reputation: 23830

Array.prototype.map():

dd.map(function(element)
{
    return { data: element };
});

Upvotes: 5

Related Questions