[英]javascript - find nested object key by its value
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"现在,我正在尝试获取值“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
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"))
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"));
You pretty much have it, just add obj[key].title === val
as mentioned by Chris G.你几乎拥有它,只需添加
obj[key].title === val
就像 Chris G 提到的那样。
Here's an ES6 one liner that returns an array of all matches.这是一个 ES6 one liner,它返回一个包含所有匹配项的数组。
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'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.