'How to filter array of object based on a key pair value in object of object?
countryList is an array of objects of country. How do I filter the objects in countryList based on the whether "title" value in secondCountryList matches the "label" in countryList. If the value in countryList matches the "title" in secondCountryList, then filter out the object in countryList.
const countryList = [
{
label: 'Brazil',
value: 1,
},
{
label: 'Peru',
value: 2,
},
{
label: 'New York',
value: 3,
},
{
label: 'Seattle',
value: 4,
},
{
label: 'Indonesia',
value: 5,
},
]
const secondCountryList = {
"195": {
"id": 195,
"title": "Brazil",
},
"198": {
"id": 198,
"title": "Peru",
},
"345": {
"id": 345,
"title": "Poland",
},
"56": {
"id": 56,
"title": "Mexico",
},
"90": {
"id": 90,
"title": "Thailand",
}
}
Example output after filtering, since Brazil and Peru was found in secondCountryList.
const countryList = [
{
label: 'New York',
value: 3,
},
{
label: 'Seattle',
value: 4,
},
{
label: 'Indonesia',
value: 5,
},
]
Solution 1:[1]
Simple solution
const countryList = [
{
label: 'Brazil',
value: 1,
},
{
label: 'Peru',
value: 2,
},
{
label: 'New York',
value: 3,
},
{
label: 'Seattle',
value: 4,
},
{
label: 'Indonesia',
value: 5,
},
];
const secondCountryList = {
"195": {
"id": 195,
"title": "Brazil",
},
"198": {
"id": 198,
"title": "Peru",
},
"345": {
"id": 345,
"title": "Poland",
},
"56": {
"id": 56,
"title": "Mexico",
},
"90": {
"id": 90,
"title": "Thailand",
}
};
let filteredListOfCountries = countryList;
for (const key in secondCountryList) {
countryList.forEach(value=>{
if(value.label === secondCountryList[key].title)
filteredListOfCountries = filteredListOfCountries.filter(value => value.label != secondCountryList[key].title)
});
}
Solution 2:[2]
You can use Array.filter, Object.keys, and Arrays.map:
const countryList = [
{
label: 'Brazil',
value: 1,
},
{
label: 'Peru',
value: 2,
},
{
label: 'New York',
value: 3,
},
{
label: 'Seattle',
value: 4,
},
{
label: 'Indonesia',
value: 5,
},
]
const secondCountryList = {
"195": {
"id": 195,
"title": "Brazil",
},
"198": {
"id": 198,
"title": "Peru",
},
"345": {
"id": 345,
"title": "Poland",
},
"56": {
"id": 56,
"title": "Mexico",
},
"90": {
"id": 90,
"title": "Thailand",
}
}
// This makes exclusionList an array of strings
const exclusionList = Object.keys(secondCountryList).map((key) => (secondCountryList[key].title))
// Then you can use the exclusionList to filter out the first array
const filteredCountryList = countryList.filter((country) => !exclusionList.includes(country.label))
/*
Should be:
const countryList = [
{
label: 'New York',
value: 3,
},
{
label: 'Seattle',
value: 4,
},
{
label: 'Indonesia',
value: 5,
},
]
*/
console.log("filteredCountryList", filteredCountryList)
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 | HuSaad |
| Solution 2 | Amats |
