javascript-通过其值查找嵌套的对象键 [英] javascript - find nested object key by its value

查看:67
本文介绍了javascript-通过其值查找嵌套的对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找包含我的值的对象的键.

I'm trying to find key of object which is containing my value.

有我的对象:

var obj = {}

obj["post1"] = {
    "title":    "title1",
    "subtitle": "subtitle1"
}

obj["post2"] = {
    "title":    "title2",
    "subtitle": "subtitle2"
}

现在,我正在尝试获取值"title2"的对象键

And now, I'm trying to get object key of value "title2"

function obk (obj, val) {
  const key = Object.keys(obj).find(key => obj[key] === val);
  return key
}

console.log(obk(obj, "title2"))

输出:

undefined

所需的输出:

post2

推荐答案

您必须访问对象的子项:

You have to access the subkey of the object:

 function obk (obj, prop, val) {
   return Object.keys(obj).find(key => obj[key][prop] === val);
 }

 console.log(obk(obj, "title", "title2"));

或者您可以搜索子对象的所有值:

Or you could search all values of the subobject:

 function obk (obj, val) {
   return Object.keys(obj).find(key => Object.values( obj[key] ).includes(val)); 
 }

 console.log(obk(obj, "title2"))

这篇关于javascript-通过其值查找嵌套的对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆