1

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.

Tsukimoto Mitsumasa
  • 541
  • 4
  • 19
  • 42

3 Answers3

8

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.

Community
  • 1
  • 1
cfs
  • 10,610
  • 3
  • 30
  • 43
  • 1
    Your `copyByValue` function can basically be replaced by `arr.slice(0)`. It will create a shallow copy of the array as well. – Felix Kling Jun 24 '13 at 19:54
  • @FelixKling Nice :) I didn't know that – cfs Jun 24 '13 at 19:55
  • @CHiRiLo Glad to have helped :) Since this answer helped you, would you mind accepting it so that other people who view the question will know it answers your question? Thanks! – cfs Jun 24 '13 at 20:02
0

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

aaronman
  • 18,343
  • 7
  • 63
  • 78
-1

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.

Incognito
  • 20,537
  • 15
  • 80
  • 120
  • 2
    I don't quite understand this. What use is the function? You don't alter the array at all? Also it's all so complicated compared to a simple for loop since you would modify the array in place. I don't get it – Liviu T. Jun 24 '13 at 20:49