How To Create 2d Array From Object (key, Value Par)
Solution 1:
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)]
Solution 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:
functionkeysAndValues(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/
Solution 3:
You can make arr
an array containing initially 2 empty arrays, then push the elements into those arrays.
functionkeysAndValues(data) {
var arr = [[], []];
for (key in data) {
if (data.hasOwnProperty(key)) {
arr[0].push(key);
arr[1].push(data[key]);
}
}
return arr;
}
Solution 4:
functionkeysAndValues(o){
var arr = newArray([] ,[]);
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]
Solution 5:
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}
functionkeyValueArray (o) {
var keys = [];
var values = [];
for (var k in o ) {
keys.push(k);
values.push(o[k]);
}
return [keys,values]
}
keyValueArray(o);
Post a Comment for "How To Create 2d Array From Object (key, Value Par)"