I have a section in which user can filter different data on drop-down select ,
I have an array of data as follows.
const data = [
{
name: 'Trump',
country: 'USA',
age: 70,
IQ: 140,
},
{
name: 'ID Amini',
country: 'Uganda',
age: 50,
},
{
name: 'Kenyatta',
country: 'Kenya',
age: 60,
},
{
name: 'Obama',
country: 'USA',
age: 45,
IQ: 141
}
]
My aim is also to be able to get all objects which do not contain IQ as you can see in the above array there are objects which do not contain IQ.
Live demo : demo
Here is what I have tried so far.
let filter = ['empty']; // passed dynamically u can pass eg Obama, kenyata etc etc
let filterTyped ='IQ' // passed dynamically als here u can pass name, country etc etc
let filtredData = filter.forEach((item) =>{
let dataFilter = data.find((element) =>{
//return all objects which does not contain IQ if Item is empyt
if(item === 'empty'){
return element[filterTyped] ==undefined;
}
// return found object
return element[filterTyped] ==item;
})
console.log('Filtred', dataFilter)
if(!dataFilter) return;
})
Any idea how to solve this issue?
4
Answers
Two ways to achieve this:
hasOwnProperty
method:Careful with using just
IQ
and!IQ
as a return value, because falsy values like0
will be false, even though that is a valid value for a field that holds a numeric value.A broken example:
Referring to your snippet, the error is that
forEach
does not return the value. Here is a dummy code, ofc you can make it better.Various examples using
filter()
andhasOwnProperty()
Is this what you are looking for?