Below is my auto mapper
var sourceObj, desObj;
var map: function (source, destination) {
var desKeys = _.keys(destination), functions;
_.extend(destination, _.pick(source, desKeys));
sourceObj = source;
desObj = destination;
functions = {
forMember: function (sourceKey, desKey) {
var keys = sourceKey.split('.'), sourceValue = sourceObj, index = 0;
// incase sourceKey is a nested object like objectA.Value
if (keys.length) {
while (index < keys.length) {
sourceValue = sourceValue[keys[index]];
index++;
}
desObj[desKey] = sourceValue;
}
else {
desObj[desKey] = sourceObj[sourceKey];
}
return functions;
}
};
return functions;
}
var mapList: function (listSource, listDestination) {
_.each(listDestination, function(destination, i){
var source = listSource[i];
map(source,destination);
});
functions = {
forMember: function (sourceKey, desKey) {
_.each(listDestination, function(destination, i){
var source = listSource[i];
map(source,destination)
.forMember(sourceKey, desKey);
});
return functions;
}
};
return functions;
}
and how to use it
var source = {
Name: 'Nguyen Tran',
Age: '30',
Address: {
Street: '121 Le Van Viet',
City: 'HCM'
}
};
var destination = {
Name: 'test',
age: '25',
Street: '',
City: ''
};
autoMapper.map(source, destination)
.forMember('Age', 'age')
.forMember('Address.Street', 'Street')
.forMember('Address.City', 'City')
Hope this work for you.
おかげで、それは完璧に動作します!私は実際に両方の呼び出しを1つの関数、すなわちextendPickに結合しました。 https://gist.github.com/jonathanconway/6193584 – Jonathan
'extendPick'関数を呼び出す方法は? –
@IlyaPalkinもしあなたがjonathanconwayの要点を意味するなら、それはちょうど '_.extendPick(objectA、objectB);'です。 'objectA'を修正して返します。 –