'How to get the name of person by passing city property from array of JS object
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");
Solution 1:[1]
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);
Solution 2:[2]
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)
Solution 3:[3]
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
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 | Roman Gavrilov |
| Solution 2 | |
| Solution 3 |
