javascript-通过其值查找嵌套对象键

时间:2018-09-26 22:13:04

标签: javascript object key

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

有我的对象:

>>> z=<abc v='a' (x='y')>
  File "<stdin>", line 1
    z=<abc v='a' (x='y')>
      ^
SyntaxError: invalid syntax
>>> 

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

var obj = {}

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

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

输出:

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

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

所需的输出:

undefined

3 个答案:

答案 0 :(得分:0)

您必须访问对象的子项:

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

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

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

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

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

答案 1 :(得分:0)

您可以使用数组映射:

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

或使用数组查找来优化搜索功能:

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

答案 2 :(得分:0)

您几乎拥有了它,只需添加Chris G提到的obj[key].title === val

这是一个ES6班轮,返回所有匹配项的数组。

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