Sunday 15 May 2011

JavaScript: Map an object to a different structure -



JavaScript: Map an object to a different structure -

my application receives info various source systems. info of same nature different structure. need unify construction , save them mutual repository.

what i'm doing below:

define construction mapping between incoming object , output object. example, source object like:

{id:'123', message:'hi', from:{id:'user1', name:'john'}},

its mapping object below:

var map = {_id:'id', message:'text', 'from.id':'by.id', 'from.name':'by.name'};

define function below:

function setsubfieldvalue(obj, field, value) { if(field && obj && value) { var = field.indexof('\.'); if( > 0) { var p = field.slice(0, i); if(!obj[p]) obj[p] = {}; setsubfieldvalue(obj[p], field.slice(i+1), value) } else obj[field] = value; } } function getsubfieldvalue(obj, field) { if(field) { var = field.indexof('\.'); if (i > 0) { var p = field.slice(0, i); if(obj[p]) { var v = field.slice(i+1); homecoming getsubfieldvalue(obj[p], v); } } else homecoming obj[field]; } } function mapobject (srcobj, fieldmap) { var obj = {}; object.keys(fieldmap).foreach(function(k) { var v = getsubfieldvalue(srcobj, k); if(v) setsubfieldvalue(obj, fieldmap[k], v); }); homecoming obj; };

the code trick of time have few drawbacks:

not supporting structures mapping of objects in array. example,

{arrayproperty:[{a:1, b:2}, {a:2, b:3}]}

my code above won't allow me map arrayproperty different construction in target object, like:

{newfield:[{field_a:1, field_b:2}, {field_a:2, field_b:3}]}

or

{newfield_a_0:1, newfield_b_0:2, newfield_a_1:2, newfield_b_1:3}

using recursive phone call , not performing well.

i'm wondering if has similar need , thought of existing libraries perform such task elegantly.

javascript

No comments:

Post a Comment