[英]Underscore.js object-object mapper?
Is there an Underscore.js function that can map one object to another object, based on the other object's properties? 是否有Underscore.js函数可以根据其他对象的属性将一个对象映射到另一个对象?
(Kind of how AutoMapper works in .NET.) ( 类似于AutoMapper在.NET中的工作方式。)
For example: 例如:
var objectA = { 'name': 'Jonathan', 'city': 'Sydney' };
var objectB = { 'name': 'Jonathan Conway', 'city': 'Sydney', 'errors': [] }
_.mapperMethod(objectB);
=> { 'name': 'Jonathan Conway', 'city': 'Sydney' };
Possibly _.extend()
: 可能
_.extend()
:
_.extend(objectA, objectB);
console.log(objectA);
// { 'name': 'Jonathan Conway', 'city': 'Sydney', 'errors': [] }
If you don't want to pick up additional keys, you can use it with _.keys()
and _.pick()
: 如果您不想获取其他密钥,可以将其与
_.keys()
和_.pick()
:
var keys = _.keys(objectA);
_.extend(objectA, _.pick(objectB, keys));
console.log(objectA);
// { 'name': 'Jonathan Conway', 'city': 'Sydney' }
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.
In the last couple of months, I have managed to create a pretty complete AutoMapper library port for TypeScript / JavaScript: AutoMapperTS. 在过去的几个月里,我设法为TypeScript / JavaScript创建了一个非常完整的AutoMapper库端口:AutoMapperTS。 The port does - amongst many other features - support flattening / nesting and asynchronous mappings.
该端口确实 - 在许多其他功能中 - 支持展平/嵌套和异步映射。
For more information about the AutoMapperTS library, including how to install it using NPM and Bower, please check out the library on GitHub: http://b.ldmn.nl/AutoMapperTS 有关AutoMapperTS库的更多信息,包括如何使用NPM和Bower安装它,请查看GitHub上的库: http : //b.ldmn.nl/AutoMapperTS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.