i have object data formatted similar following...
var origdata = {data: [ ['header1', 'header2', 'header3'], [0, 1, 2], [3, 4, 5], [6, 7, 8] ]};
what i'd reformat such data structured this...
newdata = { {'header1': 0, 'header2': 1, 'header3': 2}, {'header1': 3, 'header2': 4, 'header3': 5}, {'header1': 6, 'header2': 7, 'header3': 8} };
every time try write possible solution, lost in nested for
loops. have feeling i'm over-complicating this.
the header array origdata.data[0]
.
the data arrays can retrieved using:
dataarrays = []; (var = 1; < origdata.data.length; i++) { dataarrays.push(origdata.data[i]); }
at point, start getting confused. basically, need construct new object in for
loop contains header array elements keys, , respective data array elements values.
any appreciated. thank you!
the result should array of object rather object of objects:
newdata = [ {'header1': 0, 'header2': 1, 'header3': 2}, {'header1': 3, 'header2': 4, 'header3': 5}, {'header1': 6, 'header2': 7, 'header3': 8} ];
here how can create it:
var origdata = {data: [ ['header1', 'header2', 'header3'], [0, 1, 2], [3, 4, 5], [6, 7, 8] ]}; var newdata = []; // headers var headers = origdata.data[0]; // loop through original data arrays (var = 1 ; < origdata.data.length; i++) { // data array item var data = origdata.data[i]; // create empty item var item = {}; // combine headers values item (var j = 0; j < headers.length; j++) { item[headers[j]] = data[j]; } // add item array newdata.push(item); } // show result in stackoverflow snippet document.write(json.stringify(newdata));
Comments
Post a Comment