Reputation: 4643
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
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
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