Map array to object with depth based on separate o

2019-08-13 02:19发布

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 look as an object.

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

This object could have any depth of nested values. It is also dynamically generated.

My question is: how do I cast the values from the array to the object?

(I am trying to make a recursive function loop over the object and grab the array currently but keep running in to walls. If I get it to work I will post it, but I suspect there's an easier way to accomplish this.)

3条回答
可以哭但决不认输i
2楼-- · 2019-08-13 02:46

One of possible solutions !

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

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

function extract( 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>';

查看更多
不美不萌又怎样
3楼-- · 2019-08-13 02:52

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
  }
}

function mapObj(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);
查看更多
Evening l夕情丶
4楼-- · 2019-08-13 02:53

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
    }
};

function objectLoop(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/

查看更多
登录 后发表回答