我是角度2中打字稿的新手,我遇到了一种情况。 我有一个这种格式的json数组
needle json
[{"empId":100,"orgId":500}
{"empId":201,"orgId":566}]
以上json是按特定顺序排列的,我们需要在查找另一个json数组(Haystack)时保持该顺序
Haystack json array
[
{"empCode":21,"fname":"Ashish","Lname":"Shukla"},
{"empCode":22,"fname":"John","Lname":"Mark"},
{"empCode":21,"fname":"Vigil","Lname":"Rocker"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"},
{"empCode":21,"fname":"Erik","Lname":"Francis"},
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":21,"fname":"Feeder","Lname":"Kapoor"},
{"empCode":21,"fname":"Dan","Lname":"Rox"},
{"empCode":21,"fname":"Herb","Lname":"Deen"},
{"empCode":21,"fname":"Nate","Lname":"Diaz"},
{"empCode":21,"fname":"Nick","Lname":"Diaz"},
{"empCode":21,"fname":"Conor","Lname":"Pussy"}
]
现在我需要从haystack数组中获取这些值,这些数组的id匹配针,保持针的维持顺序
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"}
我已经实现了这个问题的解决方案,但我想我的解决方案不是最佳的,因为我使用了很多循环。有人可以建议我一个很好的解决方案。
PLS注意:员工ID的顺序应保存在针json的结果json中。
非常感谢:)
答案 0 :(得分:0)
这应该有效
public needle: any;
public hayStack: any;
this.needle = [
{"empId": 100, "orgId": 500},
{"empId": 201, "orgId": 566}
];
this.hayStack = [
{"empCode":21,"fname":"Ashish","Lname":"Shukla"},
{"empCode":22,"fname":"John","Lname":"Mark"},
{"empCode":21,"fname":"Vigil","Lname":"Rocker"},
{"empCode":201,"fname":"Rick","Lname":"Mandez"},
{"empCode":21,"fname":"Erik","Lname":"Francis"},
{"empCode":100,"fname":"Alex","Lname":"Mishra"},
{"empCode":21,"fname":"Feeder","Lname":"Kapoor"},
{"empCode":21,"fname":"Dan","Lname":"Rox"},
{"empCode":21,"fname":"Herb","Lname":"Deen"},
{"empCode":21,"fname":"Nate","Lname":"Diaz"},
{"empCode":21,"fname":"Nick","Lname":"Diaz"},
{"empCode":21,"fname":"Conor","Lname":"Pussy"}
];
const needleEmpId = this.needle.map(item => item.empId);
const hayStackEmpCode = this.hayStack.map(item => item.empCode);
const result = hayStackEmpCode.map((id, index) => {
if (needleEmpId.indexOf(id) != -1) {
return this.hayStack[index];
}
}).sort().filter(item => (item != undefined));
console.log(result);
结果
0:{empCode: 100, fname: "Alex", Lname: "Mishra"}
1:{empCode: 201, fname: "Rick", Lname: "Mandez"}