I have this array, var arr = [0, 1, 2]
and I would like to convert it into an object like this,
Object{
data: [0, 1, 2]
}
How would I get the desired output using a function perhaps? Thanks.
I have this array, var arr = [0, 1, 2]
and I would like to convert it into an object like this,
Object{
data: [0, 1, 2]
}
How would I get the desired output using a function perhaps? Thanks.
Just create an object and assign the array to one it it's properties:
var arr = [0, 1, 2];
var obj = {
data : arr
};
Or if you have an existing object, you can add the array by name:
obj['data'] = arr;
Or dot notation:
obj.data = arr;
You should be aware that these are all copying the array by reference, so any updates you make to the arr
variable will update obj.data
as well. If you want to copy by value, you could do something like:
var obj = {
data: arr.slice(0)
};
See this JSFiddle for an example of copying by reference versus copying by value. You could read the answer to this question for more information about copying by value vs copying by reference.
You can do this very easily like this var obj = {data:arr};
However I think you should consider what purpose you are using the object for. An array is technically already a javascript object so you may not even need to do this
It's quite easy you just need a factory for it.
function arrayToObjectTransformationFactory($array, $transformationTransportProtocol){
return function($array){
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
};
}
$array.forEach($transformationTransportProtocol)
return { "data": $array };
}($array);
}
arrayToObjectTransformationFactory([0, 1, 2], function($element, $index, $array){
var quux = [];
quux.push($array[$index]);
});
Should work cross browser and with jQuery too.