我处于这样一种情况,我必须设计一个具有已定义模式的对象映射器,即我将得到一个对象数组的响应,这是对象映射的模式,如下所示。
[
{
"fieldToMap":"entityName",
"fieldName":"name"
},
{
"fieldToMap":"entityNumber",
"fieldName":"number"
}
]
当我点击任何api端点并得到这样的响应时,
[
{
"name":"something",
"number":"something"
},
{
"name":"something",
"number":"something"
}
]
我必须将它映射到一个对象并创建一个像这样的新对象
[
{
"entityName":"something",
"entityNumber":"something"
},
{
"entityName":"something",
"entityNumber":"something"
}
]
如何解决这个问题?是循环响应并用模式中提供的键替换响应键的好方法,还是有其他方法可以使用?任何帮助都会受到赞赏。谢谢
答案 0 :(得分:1)
类似这样的事情
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
})
}
答案 1 :(得分:0)
试试这样:
getAll() {
return this.http.get('sample.json')
.map(res => <SchemaModel[]>res.json());
}