javascript - find nested object key by its value

前端 未结 3 1587
忘了有多久
忘了有多久 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条回答
  •  猫巷女王i
    2021-01-29 02:07

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

提交回复
热议问题