I have JSON data from a Google sheet in a 3D array like this:
const values = [
[
// useless first array
],
[
'timestamp_dont_want',
'bird',
'',
'',
'easy',
'foot'
],
[
'timestamp_dont_want',
'bee',
'celery'
],
// lots of other arrays
[
'timestamp_dont_want',
'bat',
'chocolate',
'droid',
'',
'finger',
'',
'hella cool',
'indiana'
]
];
The maximum length of any given array is 12. Other than the entire first array and index 0 of every following array, each value (that is present and not empty) in an array corresponds to a desired object key label I have stored as 11 strings in another array:
const labels = [
'label_b',
'label_c',
'label_d',
'label_e',
'label_f',
'label_g',
'label_h',
'label_i',
'label_j',
'label_k',
'label_l'
];
Some arrays have all the values I need and many have empty values or stop at a certain index. I would like to create a new array of objects, containing only the useful and present data, that would be organized like this:
const organized = [
{
label_b: 'bird',
label_e: 'easy',
label_f: 'foot'
},
{
label_b: 'bee',
label_e: 'celery'
},
// lots of other objects
{
label_b: 'bat',
label_c: 'chocolate',
label_d: 'droid',
label_f: 'finger',
label_h: 'hella cool',
label_i: 'indigo'
}
];
I wrote a function, but it doesn't feel very elegant:
function sort (arr3d, arrKeys) { // Passing values and labels constants from above
let organized = []; // Initiate array
for (var i = 1; i < arr3d.length; i++) { // For each array of values, starts at 1 to ignore first useless array
organized.push({}); // Create empty objects
}
for (var j = 0; j < arrKeys.length; j++) { // Outer loop once for each unique object key
for (var k = 1; k < arr3d.length; k++) { // Inner loop for each array of values, starts at 1 to ignore first useless array
if (arr3d[k][j + 1]) { // Testing presence of value before writing in next step, ignoring index 0 of each array
organized[k - 1][arrKeys[j]] = arr3d[k][j + 1].trim(); // Craete new key in object; trim value from associated array and assign to key
}
}
}
console.log(organized); // Prove it worked
}
Any ideas about how to refactor or optimize? Maybe you can teach me about using a new JS method.