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");
CodePudding user response:
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);
CodePudding user response:
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");
CodePudding user response:
I made one little change to your code that you provided and it works fine now
const arrofobj = [
{city:"paris", name: "chris"},
{city:"berlin", name: "john"},
{city:"moscow", name: "jev"}
];
function fetchname(cityname) {
arrofobj.forEach((val)=>{if(Object.keys(val)[0] == "city") {if (val.city
== cityname) console.log(val.name)}})//works fine now
}
fetchname("paris");
Object.keys returns an array of keys of the object city key is at first index hence [0] since you used object.keys and were comparing it without [0] it was comparing the array object hence getting false and not printing
CodePudding user response:
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)