我有2个对象数组。 他们是
array1 = [{
id:2,
name:"person2"
},{
id:3,
name:"person3"
},
{
id:4,
name:"person4"
},
{
id:5,
name:"person5"
},
];
array2 = [
{
empId:2,
isdeleted:false
},
{
empId:4,
isdeleted:false
},
{
empId:3,
isdeleted:true
}];
我需要array1中的对象,其id与array2的empId匹配并且被删除为false。预先感谢。
答案 0 :(得分:1)
let array1 = [{
id: 2,
name: "person2"
}, {
id: 3,
name: "person3"
},
{
id: 4,
name: "person4"
},
{
id: 5,
name: "person5"
},
];
let array2 = [{
empId: 2,
isdeleted: false
},
{
empId: 4,
isdeleted: false
},
{
empId: 3,
isdeleted: true
}
];
let filteredArray = array1.filter(a => array2.some(b => b.empId === a.id && !b.isdeleted));
console.log(filteredArray);
答案 1 :(得分:0)
尝试
let result = [];
array1.forEach(function(element1){
array2.forEach(function(element2){
if (element1.id === element2.empId && !element2.isdeleted){
result.push(element);
}
});
});
console.log(result);
答案 2 :(得分:0)
您可以尝试如下操作:
let array1 = [
{ id:2, name:"person2"},
{ id:3, name:"person3"},
{ id:4, name:"person4"},
{ id:5, name:"person5"}
];
let array2 = [
{ empId:2, isdeleted:false},
{ empId:4, isdeleted:false},
{ empId:3, isdeleted:true}
];
let result = array1.reduce((output, item) => {
if (array2.find((item2) => !item2.isdeleted && item.id === item2.empId)) output.push(item);
return output;
}, []);
console.log(result);
答案 3 :(得分:0)
您可以将Array.filter()
与find()
一起在array2
中查找具有该条件的对象:
var array1 = [{
id: 2,
name: "person2"
}, {
id: 3,
name: "person3"
},
{
id: 4,
name: "person4"
},
{
id: 5,
name: "person5"
},
];
var array2 = [{
empId: 2,
isdeleted: false
},
{
empId: 4,
isdeleted: false
},
{
empId: 3,
isdeleted: true
}
];
var res = array1.filter((obj1)=>{
var exist = array2.find((obj2)=> (obj1.id == obj2.empId && !obj2.isdeleted));
return exist;
});
console.log(res);