I am dealing with some JSON data that I am retrieving from a database. If the result contains a single value, it creates a single object. If there are multiple values, it creates an array of objects.
My issue is that having to try and handle this becomes a problem when dealing with loops.
Example Data:
// Single result from DB
var obj = {
"records": {
"recordID": 1,
"recordName": 'test'
}
}
// Multiple results from DB
var obj = {
"records": [{
"recordID": 1,
"recordName": 'test'
}, {
"recordID": 2,
"recordName": 'test again'
}]
}
I have a function that loops over all of the records for example and this becomes problematic when we only have one result because we are no longer looping over an array.
Due to some of my objects being pretty large, I am trying to come up with a function that I can initialize my object with when I get it back from the database before handling it.
This function would loop through all of the keys and check to see if the key exists in an array of "Does this need to be an array?" flags. If it finds a match, check to see if its a single object and if so, convert it to an array of that single object.
Here is some pseudo code of what I am trying to do:
// Input
var obj = {
"records": {
"recordID": 1,
"recordName": 'test'
},
"photos": {
"photoID": 1,
"photoName": 'test flower'
},
"leaveMeAlone": {
"nopeID": 1,
"nopeName": 'tester'
}
}
function convertToArray(obj) {
var keysToArray = ['records', 'photos'];
// Loop over keys
for (var k in obj) {
// Properties
if (obj.hasOwnProperty(k)) {
// This key is in our array.
if (keysToArray.indexOf(k) > -1) {
// If this is a single object, turn it into an array containing a single object
if (!Array.isArray(obj[k])) {
// Turn this value into an array of the single object
/* Stuck Here */
}
}
}
}
/* Return
var obj = {
"records": [{
"recordID": 1,
"recordName": 'test'
}],
"photos": [{
"photoID": 1,
"photoName": 'test flower'
}],
"leaveMeAlone": {
"nopeID": 1,
"nopeName": 'tester'
}
}
*/
}
// run
convertToArray(obj);