javascript - find nested object key by its value

只愿长相守 提交于 2021-02-05 11:01:06

问题


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

There is my object:

var obj = {}

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

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

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"))

Output:

undefined

Desired output:

post2

回答1:


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"))



回答2:


You can use array map:

var obj = {}

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

obj["post2"] = {
    "title":    "title2",
    "subtitle": "subtitle2"
}
//console.log(obj);
function obk (obj, val) {
    var result = "";
    Object.keys(obj).map(key => {
        if(obj[key].title === val)
            result = key;
    });
    return result;
}

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

Or use array find to optimize searching function:

var obj = {}

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

obj["post2"] = {
    "title":    "title2",
    "subtitle": "subtitle2"
}
//console.log(obj);
function obk (obj, val) {
    result = Object.keys(obj).find(key => {
        if(obj[key].title === val)
            return key;
    });
    return result;
}

console.log(obk(obj, "title1"));



回答3:


You pretty much have it, just add obj[key].title === val as mentioned by Chris G.

Here's an ES6 one liner that returns an array of all matches.

var obj = {}

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

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

const filterByTitle = (obj, title) => 
  Object.values(obj).filter(o => o.title === title);

console.log(filterByTitle(obj, 'title1'))


来源:https://stackoverflow.com/questions/52526712/javascript-find-nested-object-key-by-its-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!