I have this array of objects
const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
I want to write a function when I pass paris, I want to get back chris, how to achieve this?
Here is what I have tried
const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
function fetchname(cityname) {
arrofobj.forEach((val)=>{if(Object.keys(val) == "city") {if (val.city == cityname) console.log(val.name)}})//nothing is printed
}
fetchname("paris");
You able to use filter
const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
console.log(arrofobj.filter((arro) =>arro.city == 'paris')[0].name);
you must use filter method as follow:
const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
function getByCity(city) {
var result = arrofobj.filter(obj => {
return obj.city === city
})
return result;
}
console.log(getByCity('paris')[0].name)
I think it will help you Hvae you any question in this code. Comment below
const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
function fetchname(cityname) {
const findValue = arrofobj.find((value)=>value.city==cityname)
console.log(findValue)
return findValue.name ?? ""
}
fetchname("paris");