Efrain Sanjay Adhikary
Efrain Sanjay Adhikary

Reputation: 326

Finding the object key with the value inside the array?

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

Answers (3)

jo_va
jo_va

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

Nina Scholz
Nina Scholz

Reputation: 386550

You could get the keys and find with includes.

Methods:

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

Maheer Ali
Maheer Ali

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

Related Questions