0

For example, I have object:

o = {a: 1, b: 2, c: 3}

and I need to write function that returns 2d array:

arr = [['a', 'b', 'c'], [1, 2, 3]];

For now I have function that creates simple array, but I don't know how to go from there (knowledge not found). The function:

function keysAndValues(o){
  var arr= []; 
  for(key in data)
  {   
      arr.push(key);
      //or
      arr.push(data[key]);

  }
  return arr;
};

How can I create 2d array?

EDIT

All the answers are correct, and I have learned couple of new things. Thank you a lot guys. Bad thing is only one can get green arrow, so it will go to the first one who gave answer.

4

5 回答 5

2

There needs to be three arrays, an outer array that contains two arrays at indexes 0 and 1. Then just push to the appropriate array:

function keysAndValues(data){
  var arr= [[],[]]; //array containing two arrays
  for(key in data)
  {   
      arr[0].push(key);
      arr[1].push(data[key]);
  }
  return arr;
};

JS Fiddle: http://jsfiddle.net/g2Udf/

于 2013-10-10T16:22:24.147 回答
2

You can make arr an array containing initially 2 empty arrays, then push the elements into those arrays.

function keysAndValues(data) {
  var arr = [[], []];
  for (key in data) {
    if (data.hasOwnProperty(key)) {
      arr[0].push(key);
      arr[1].push(data[key]);
    }
  }
  return arr;
}
于 2013-10-10T16:22:27.913 回答
2

I will go the library approach since everyone wrote their take on the subject, using underscore's _.keys and _.values

_.keys(o);

will return o keys, while

_.values(o)

will return o values. So from here you could do

arr = [_.keys(o), _.values(o)]
于 2013-10-10T16:25:33.220 回答
1
function keysAndValues(o){
var arr = new Array([] ,[]); 
for(key in o)
  {   
    arr[0].push(key);
    arr[1].push(o[key]);

  }
return arr;
};

You basically want an array containing two arrays: 0: all keys 1: all values

So push all keys into arr[0] and all values into arr[1]

于 2013-10-10T16:21:24.430 回答
1

You can use a for in loop to iterate over your object, add the keys and values to individual arrays, and return an array containing both of these generated arrays:

var o = {a: 1, b: 2, c: 3}

function keyValueArray (o) {
  var keys = [];
  var values = [];

  for (var k in o ) {
    keys.push(k);
    values.push(o[k]);
  }
  return [keys,values]
}

keyValueArray(o);

jsfiddle

于 2013-10-10T16:26:21.320 回答