查找数组中包含值的对象键?

时间:2019-03-07 15:26:27

标签: javascript object

我知道有些人可能会发现这很容易。但这似乎很难开始。如果我有数组,我可以轻松完成过滤器。

让我说我有这个物体

    const mapData = {family: ["gender", "ethnics"], house: ["wardNumber","livingType"]}

现在,如果我有atribute = "gender",该如何找到密钥family

如果我有atribute = "livingType",那么我需要House;

这里有Javascript专业人士吗?

预先感谢

3 个答案:

答案 0 :(得分:3)

您可以获取密钥并找到包含项。

方法:

const
    mapData = { family: ["gender", "ethnics"], house: ["wardNumber", "livingType"] },
    attribute = "gender",
    key = Object
        .keys(mapData)
        .find(k => mapData[k].includes(attribute));

console.log(key);   

答案 1 :(得分:1)

您可以使用Object.keys()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"))

答案 2 :(得分:1)

您可以使用Object.entries()Array.find()Array.includes()Array.shift()来做到这一点。

如果找不到该值,则将返回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'));