'How to get array of objects based on object and array list in javascript
I have an array of object, a object, and an arraylist.
I have to get the array of objects based on conditions using javascript:
Fetch the array of objects if the
valueproperty matches with objectitemCheck if the
codevalue exists in the arraylistarraylist, if exists return array ibjectElse return empty
var arrobj1 =[
{id:1, name: zen, code: "SP", value: 100},
{id:2, name: abi, code: "IN", value: 200},
{id:3, name: lisa, code: "SG", value: 200}
]
var arraylist =["IN"]
var obj1={
id:34, code: "SP", country: "mexico", item: 200
}
Expected Output:
// value & item matches, code does not exists so empty []
var arrobj2 =[
{id:1, name: zen, code: "SP", value: 300},
{id:2, name: abi, code: "SP", value: 200},
{id:3, name: lisa, code: "SG", value: 100}
]
var arraylist =["IN"]
var obj2={
id:34, code: "SP", country: "italy", item: 100
}
Expected Output
// value & item matches, code matches
[
{id:3, name: lisa, code: "SG", value: 100}
]
I have tried using below code:
var result = arrobj1.some(e => {
if (e.value === obj.item &&
(arraylist.includes(e.code)){
return true;
}
return false;
});
Solution 1:[1]
First filter items, then use some.
let filtered = arrobj1.filter(({value}) => value == obj1.item)
let result = filtered.some(({code}) => arraylist.includes(code)) ? [] : filtered
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user14967413 |
