I'm trying to get single object with different item based by the id
from compared result of two array of objects.
Here's the case:
First Array
[
{
"id": "792657571767910421",
"type": 0,
"allow": "0",
"deny": "0"
},
{
"id": "1020443938668171294",
"type": 0,
"allow": "0",
"deny": "377959221312"
},
{
"id": "791708642813411358",
"type": 0,
"allow": "0",
"deny": "0"
}
]
Second Array
[
{
"id": "792657571767910421",
"type": 0,
"allow": "1024",
"deny": "0"
},
{
"id": "1020443938668171294",
"type": 0,
"allow": "0",
"deny": "377959221312"
},
{
"id": "791708642813411358",
"type": 0,
"allow": "0",
"deny": "0"
},
]
Expected Output
[
{
"id": "792657571767910421",
"type": 0,
"allow": "1024",
"deny": "0"
},
]
Different value
// First array
{
"allow": "0"
}
// Second array
{
"allow": "1024"
}
Can anyone help me? Thank you.
CodePudding user response:
You will have to use custom filter logic:
Logic:
- Loop over
arr2
or the array you need output from. - Test items with
param2
. On match:- Loop over
arr1
or the other array. - Find the object with same ID.
- On finding,
- Test item with
param1
. Return test value.
- Test item with
- Else return false
- Loop over
function filter(arr1, arr2, param1, param2) {
const test = (param, item) =>
Object
.entries(param)
.every(([k, v]) => item[k] === v)
return arr2.filter((itemB) => {
if (test(param2, itemB)) {
const itemA = arr1.find(({id}) => id === itemB.id)
return !!itemA ? test(param1, itemA) : false
}
return false
})
}
const arr1 = [{"id": "792657571767910421","type": 0,"allow": "0","deny": "0"},{"id": "1020443938668171294","type": 0,"allow": "0","deny": "377959221312"},{"id": "791708642813411358","type": 0,"allow": "0","deny": "0"}]
const arr2 = [{"id": "792657571767910421","type": 0,"allow": "1024","deny": "0"},{"id": "1020443938668171294","type": 0,"allow": "0","deny": "377959221312"},{"id": "791708642813411358","type": 0,"allow": "0","deny": "0"},]
const param1 = {"allow": "0"}
const param2 = {"allow": "1024"}
console.log(filter(arr1, arr2, param1, param2))