Reputation: 326
I know Some people might find this very easy. But It seems to be very difficult to start. If i have array i could have easily done with filter.
Lets say i have this object
const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
Now if I have atribute = "gender"
How can i find the key family
.
if I have atribute = "livingType"
Then i need House
;
Any Javascript pro here?
Thanks in advance
Upvotes: 0
Views: 60
Reputation: 13964
You can do it with Object.entries()
, Array.find()
, Array.includes()
and Array.shift()
.
If the value is not found, this will return undefined
.
const data = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
const getKey = val =>
(Object.entries(data).find(([k, v]) => v.includes(val)) || []).shift();
console.log(getKey('gender'));
console.log(getKey('livingType'));
console.log(getKey('non-existing-value'));
Upvotes: 1
Reputation: 386550
You could get the keys and find with includes.
Methods:
Object.keys
for getting own keys from an object,
Array#find
for finding an item with a callback,
Array#includes
, this checks if an item exists in an array.
const
mapData = { family: ["gender", "ethnics"], house: ["wardNumber", "livingType"] },
attribute = "gender",
key = Object
.keys(mapData)
.find(k => mapData[k].includes(attribute));
console.log(key);
Upvotes: 3
Reputation: 36564
You can use Object.keys()
and filter()
const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}
const findKey = (obj,attr) => Object.keys(obj).filter(k => obj[k].includes(attr))[0]
console.log(findKey(mapData,"gender"))
console.log(findKey(mapData,"livingType"))
Upvotes: 1