JavaScript convert specified single objects into array -
i dealing json
data retrieving database. if result contains single value, creates single object. if there multiple values, creates array of objects.
my issue having try , handle becomes problem when dealing loops.
example data:
// single result db var obj = { "records": { "recordid": 1, "recordname": 'test' } } // multiple results db var obj = { "records": [{ "recordid": 1, "recordname": 'test' }, { "recordid": 2, "recordname": 'test again' }] }
i have function loops on of records example , becomes problematic when have 1 result because no longer looping on array.
due of objects being pretty large, trying come function can initialize object when database before handling it.
this function loop through of keys , check see if key exists in array of "does need array?" flags. if finds match, check see if single object , if so, convert array of single object.
here pseudo code of trying 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 on keys (var k in obj) { // properties if (obj.hasownproperty(k)) { // key in our array. if (keystoarray.indexof(k) > -1) { // if single object, turn array containing single object if (!array.isarray(obj[k])) { // turn value array of 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);
you take iterative , recursive approach converting given properties array, if not array.
if keys unique, use return deleting properties of array, or changing the path depth first breadth first search.
function convert(object, keys) { object.keys(object).foreach(function (k) { if (object[k] && typeof object[k] === 'object') { convert(object[k], keys); } if (keys.indexof(k) !== -1 && !array.isarray(object[k])) { object[k] = [object[k]]; } }); } var object = { records: { recordid: 1, recordname: 'test' }, photos: { photoid: 1, photoname: 'test flower' }, leavemealone: { nopeid: 1, nopename: 'tester' }, nested: { convert: { foo: 1, bar: 2 } } }, keys = ['records', 'photos', 'convert']; convert(object, keys); console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment