具有已定义模式的对象映射 Angular 2/4
Object mapping with a defined schema Angular 2/4
我处于一种情况,我必须设计一个具有定义模式的对象映射器,即我将得到一个对象数组的响应,这是对象映射的模式。
[
{
"fieldToMap":"entityName",
"fieldName":"name"
},
{
"fieldToMap":"entityNumber",
"fieldName":"number"
}
]
当我点击任何 api 端点并得到这样的响应时,
[
{
"name":"something",
"number":"something"
},
{
"name":"something",
"number":"something"
}
]
我必须将它映射到一个对象并像这样创建一个 nw 对象
[
{
"entityName":"something",
"entityNumber":"something"
},
{
"entityName":"something",
"entityNumber":"something"
}
]
如何解决这个问题?遍历响应并用模式中提供的键替换响应的键是好方法还是有任何其他可以使用的方法?任何帮助都是 appreciated.Thank 你
这样试试:
getAll() {
return this.http.get('sample.json')
.map(res => <SchemaModel[]>res.json());
}
像这样
var schema = [
{
"fieldToMap":"entityName",
"fieldName":"name"
},
{
"fieldToMap":"entityNumber",
"fieldName":"number"
}
]
var response = [
{
"name":"something",
"number":"something"
},
{
"name":"something",
"number":"something"
}
];
var result = mapObject(response, schema);
function mapObject(data, schema) {
return data.map(function(el) {
var obj = {};
schema.forEach(function(s) {
obj[s.fieldToMap] = el[s.fieldName];
});
return obj
})
}
我处于一种情况,我必须设计一个具有定义模式的对象映射器,即我将得到一个对象数组的响应,这是对象映射的模式。
[
{
"fieldToMap":"entityName",
"fieldName":"name"
},
{
"fieldToMap":"entityNumber",
"fieldName":"number"
}
]
当我点击任何 api 端点并得到这样的响应时,
[
{
"name":"something",
"number":"something"
},
{
"name":"something",
"number":"something"
}
]
我必须将它映射到一个对象并像这样创建一个 nw 对象
[
{
"entityName":"something",
"entityNumber":"something"
},
{
"entityName":"something",
"entityNumber":"something"
}
]
如何解决这个问题?遍历响应并用模式中提供的键替换响应的键是好方法还是有任何其他可以使用的方法?任何帮助都是 appreciated.Thank 你
这样试试:
getAll() {
return this.http.get('sample.json')
.map(res => <SchemaModel[]>res.json());
}
像这样
var schema = [
{
"fieldToMap":"entityName",
"fieldName":"name"
},
{
"fieldToMap":"entityNumber",
"fieldName":"number"
}
]
var response = [
{
"name":"something",
"number":"something"
},
{
"name":"something",
"number":"something"
}
];
var result = mapObject(response, schema);
function mapObject(data, schema) {
return data.map(function(el) {
var obj = {};
schema.forEach(function(s) {
obj[s.fieldToMap] = el[s.fieldName];
});
return obj
})
}