Array object searching based on given city name
This function should search record of those employees whose city name is exist in data array object
by Sunny SM
JavaScript
const employees = [
{
"emp_id":101,
"empname":"Ram",
"salary":60000,
"address" :
{
"street-no":20,
"plot-no":121,
"city":"pune",
"contact" :
{
"landline" : 2292099,
"mobile" : 8907632178
}
}
},
{
"emp_id":102,
"empname":"Shyam",
"salary":50000,
"address" :
{
"street-no":12,
"plot-no":221,
"city":"mumbai"
}
},
{
"emp_id":103,
"empname":"Lakhan",
"salary":40000,
"address" :
{
"street-no":11,
"plot-no":432,
"city":"pune"
}
},
{
"emp_id":104,
"empname":"Snigdha",
"salary":60000,
"address" :
{
"street-no":21,
"plot-no":222,
"city":"delhi"
}
}
];
const getFilteredEmployee = (data, search) => {
if (data && data.length) {
if (search) {
const result = [];
const record = data.forEach(emp => {
const { address: { city } } = emp;
if (city === search) {
console.log('address.city, search', city, search);
result.push(emp);
}
});
return result;
} else return data;
}
}
console.log(getFilteredEmployee(employees, 'pune'));