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' } ]
1
  • 2
    think this might be what I want Commented Sep 3, 2015 at 0:14

3 Answers 3

5

Array.prototype.map():

dd.map(function(element)
{
    return { data: element };
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

Try this instead:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.