Created
November 9, 2016 06:25
-
-
Save sarfarazansari/7e8ae05168b80b36016eb1c561a82f73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//assuming array look like this. | |
var arr = [ | |
["Status", "Name", "Marks", "Position"], | |
["active", Sarfaraz, 10.0, "Front-end-dev"], | |
["active", John, 10.0, "Front-end-dev"], | |
["deactive", Raganar, 10.0, "UI designer"], | |
]; | |
console.log (arrToObject(arr)); | |
//create JSON object from 2 dimensional Array | |
function arrToObject (arr){ | |
//assuming header | |
var keys = arr[0]; | |
//vacate keys from main array | |
var newArr = arr.slice(1, arr.length); | |
var formatted = [], | |
data = newArr, | |
cols = keys, | |
l = cols.length; | |
for (var i=0; i<data.length; i++) { | |
var d = data[i], | |
o = {}; | |
for (var j=0; j<l; j++) | |
o[cols[j]] = d[j]; | |
formatted.push(o); | |
} | |
return formatted; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That was quite minified, which could be confusing.
We can re-write it to be more readable. And put it into a function similar to the OP.
And the concise version would be: