简体   繁体   中英

How to create 2d array from object (key, value par)

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.

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/

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;
}

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)]
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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM