我有两个数组,名称分别为changeemployeesarray和allemployees。
var changedemployeesarray = [
{
"empId": "1126",
"name": "sam"
},
{
"empId": "1128",
"name": "mike"
},
{
"empId": "1134",
"name": "steve"
}
]
var allemployees = [
{
"empFullName": "sam Raj",
"empInfo": {
"empSeq": "1126",
"createDate": "2018-10-17"
},
"modfiedDate": "2018-10-24"
},
{
"empFullName": "mike",
"empInfo": {
"empSeq": "1128",
"createDate": "2018-10-17"
},
"modfiedDate": "2018-10-24"
},
{
"empFullName": "steve",
"empInfo": {
"empSeq": "1134",
"createDate": "2018-10-17"
},
"modfiedDate": "2018-10-24"
}
]
如果allemployees数组中存在/找到了changeemployeesarray的empId,我想插入到updatearray中。 如果找不到,将其插入createarray
我已经遵循了这种方法,有没有更好的方法
https://jsfiddle.net/o2gxgz9r/74296/
预期输出
updatearray
[{"empId":"1126","name":"sam"},{"empId":"1128","name":"mike"}]
createarray
[{"empId":"1136","name":"steve"}]
答案 0 :(得分:3)
答案 1 :(得分:0)
您可以尝试关注。它解决了线性复杂度问题。
changedemployeesarray
allemployees
并在匹配项上填充updatearray
,并从上面创建的对象中删除条目obj
中所有其余条目均丢失,即created
。以此填充createarray
。
var changedemployeesarray = [{"empId":"1126","name":"sam"},{"empId":"1128","name":"mike"},{"empId":"1136","name":"steve"}];
var allemployees = [{"empFullName":"sam Raj","empInfo":{"empSeq":"1126","createDate":"2018-10-17"},"modfiedDate":"2018-10-24"},{"empFullName":"mike","empInfo":{"empSeq":"1128","createDate":"2018-10-17"},"modfiedDate":"2018-10-24"},{"empFullName":"steve","empInfo":{"empSeq":"1134","createDate":"2018-10-17"},"modfiedDate":"2018-10-24"}];
// Step 1 - Create object from changedemployeesarray
let obj = changedemployeesarray.reduce((a,c) => Object.assign(a, {[c.empId] : c}), {});
// Step 2 - Populate updatearray in case of match
let updatearray = allemployees.reduce((a,c) => {
if(obj[c.empInfo.empSeq]) {
a.push(obj[c.empInfo.empSeq]);
delete obj[c.empInfo.empSeq];
}
return a;
}, []);
// Step 3 - Populate createarray with remaining values (missing means created)
let createarray = Object.values(obj);
console.log(createarray);
console.log(updatearray);
答案 2 :(得分:0)
由于您将UNIQUE键设置为“ empid”,因此最佳实践是创建单个数组并在后端使用“ ON DUPLICATE KEY UPDATE”。如果empid已经存在,它将更新条目。