地图数组基于独立的对象,深入到对象 [英] Map array to object with depth based on separate object
问题描述
我有一个数据数组(在现实中解析CSV从MySQL转储头)
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.)
推荐答案
下面是做到这一点的方法之一。它的工作原理为您presented的情况。
Here is one way to do it. It works for the case you presented.
提琴: 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);
这篇关于地图数组基于独立的对象,深入到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!