Skip to content Skip to sidebar Skip to footer

Map Array To Object With Depth Based On Separate Object

I have an array of data (in reality a parsed CSV dump from MySQL with headers) ['adam', 'smith', 'honda', 'civic'] I have an object which defines how that array of data should loo

Solution 1:

Here is one way to do it. It works for the case you presented.

fiddle: http://jsfiddle.net/wy0doL5d/8/

var arr = ['adam', 'smith', 'honda', 'civic']

var obj = {
  first_name : 0,
  last_name: 1,
  car : {
    make: 2,
    model: 3
  }
}

functionmapObj(o, a)
{
    Object.keys(o).forEach(function(key){
        var objType = typeof(o[key]);
        if(objType === "object")
        {
            mapObj(o[key], a);
        }
        else
        {
            o[key] = a[o[key]];
        }
    });

}

mapObj(obj, arr);

Solution 2:

You could try something like this:

var myarray = ['adam', 'smith', 'honda', 'civic'];
var myobject = {
    first_name: 0,
    last_name: 1,
    car: {
        make: 2,
        model: 3
    }
};

functionobjectLoop(obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] == 'number') {
                obj[key] = myarray[obj[key]];
            } else {
                objectLoop(obj[key]);
            }
        }
    }
    return obj;
}

console.log(objectLoop(myobject));

This was a quick write. There may be some use cases I didn't account for but it does work for your data above. It can def be expanded on.

Fiddle: http://jsfiddle.net/qyga4p58/

Solution 3:

One of possible solutions !

var arr =['adam', 'smith', 'honda', 'civic'];
var obj = {
  first_name : 0,
  last_name: 1,
  car : {
    make: 2,
    model: 3
  }
}

functionisNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

functionextract( argObj , argArr){
  var o = {};
  Object.keys( argObj ).forEach(function( k ){
      
      var curDef = argObj[k];
      if(isNumber( curDef ) ){
        o[k] = argArr[ curDef ];
        return;
      }
      o[k] =  extract( curDef , argArr); 
  })
  return o;
}
var newO = extract(obj, arr);

console.dir( newO );
document.body.innerHTML+= '<pre>' + JSON.stringify(newO , null , ' ') + '</pre>';

Post a Comment for "Map Array To Object With Depth Based On Separate Object"