假设我想实现这个功能:
function myMapper(data, mapping) { }
输入为:
data = { hello : 'hi' , embedded : { prop1 : 'hiiiii' } };
mapping = { hello : 'HELLO', 'embedded.prop1' : 'embedded.propOne' };
输出结果为:
res = myMapper(data, mapping);
res is { HELLO : 'hi' , embedded : { propOne : 'hiiiii' } };
说清楚:
答案 0 :(得分:3)
实际上很简单:
function myMapper(data, mapping, reverse) {
var res = {};
for (var n in mapping) {
var from = (reverse ? mapping[n] : n).split("."),
to = (reverse ? n : mapping[n]).split(".");
for (var o=res, p=data, i=0; i<from.length-1; i++) {
o = o[to[i]] || (o[to[i]] = {});
p = p && p[from[i]];
}
o[to[i]] = p && p[from[i]] || null;
}
return res;
}
答案 1 :(得分:1)
这是您可以使用的概要。但在潜入之前,如果是作业,请尝试自己解决。
function myMapper(data, mapping) {
var key, mkey, ret = {};
for (key in data) {
mkey = mapping[key];
//check if there is a direct mapping
if (mkey !== undefined) {
ret[mkey] = data[key];
} else if (/* check for dot in mkey */) {
//use similar construct as above but parse mkey
ret = // assign to the new key
} else if ... etc.
}
return ret;
}