Let's say I have an input and typed hosu so what I want to be able to do is filter through this objects and get the value for it.So I should get 321234 which is the pincode for hosurRoad. How do i achieve this?
const recoganizedAreas = {
'hsr':'560102',
'bypanahalli':'676667',
'marathalli':'667776',
'hosurRoad':'321236',
'teachersColony':'560101'
};
const areas = Object.keys(recoganizedAreas);
CodePudding user response:
Maybe you can use recoganizedAreas[ areas[3] ]
to get value for hosurRoad of recoganizedAreas
Also you can reach of 3
for hosurRoad of areas by using areas.indexOf("hosurRoad")
console.log(recoganizedAreas[ areas[3] ])
"321236"
CodePudding user response:
You can just get the key and access the value from Object directly.
const text = 'hosu';
const recoganizedAreas = {
'hsr':'560102',
'bypanahalli':'676667',
'marathalli':'667776',
'hosurRoad':'321236',
'teachersColony':'560101'
};
const key = Object.keys(recoganizedAreas).find(key => key.includes(text));
if(recoganizedAreas[key]) {
console.log(recoganizedAreas[key])
}
CodePudding user response:
I don't quite understand the request because if you have an object you can just access the property you are looking for.
If you have to do some business logic based on key value you can use Object.entries to filter the object by key
here some example
const recoganizedAreas = {
'hsr':'560102',
'bypanahalli':'676667',
'marathalli':'667776',
'hosurRoad':'321236',
'teachersColony':'560101'
};
const areas = Object.keys(recoganizedAreas)
const hosurPinCode = recoganizedAreas.hosurRoad
console.log(hosurPinCode)
const objectFilteredByKey = (key) => Object.fromEntries(
Object.entries(recoganizedAreas).filter(([k, _]) => k === key)
)
console.log(objectFilteredByKey('hosurRoad'))
CodePudding user response:
I think this is the solution you are looking for
const recoganizedAreas = {
'hsr':'560102',
'bypanahalli':'676667',
'marathalli':'667776',
'hosurRoad':'321236',
'teachersColony':'560101'
};
const typed = 'hosu'
const foundKey = Object.keys(recoganizedAreas).find(key => key.includes(typed))
const foundValue = recoganizedAreas[foundKey] || "Not found"
console.log(foundValue)
CodePudding user response:
I didn't read the question too thoroughly but I think you can just use ones if the following:
Object.values(obj)
// Or
Object.entries(obj)