javascript - find nested object key by its value

前端 未结 3 1575
忘了有多久
忘了有多久 2021-01-29 01:27

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

There is my object:

var obj = {}

obj[\"post1\"] = {
    \"title\":    \"title1\",
    \         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-29 02:10

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

提交回复
热议问题