comparing a string to a nested object

lurf :

I am pretty new to learning to code. So sorry if this is a stupid question.

I have a nested object database that I want to search for a character name and then return to me who's character it is. But, so far, I can only find solutions that search the top level objects or are for arrays and I am running out of ideas. Is it possible to search in depth for a name like 'Farah' and then somehow get 'olis characters' back?

Thanks in advance for any advice you guys might have!

{
  "olis characters": {
    "0": {
      "name": "Farah",
      "class": "rogue",
      "level": 74
    },
    "1": {
      "name": "Grop",
      "class": "paladin",
      "level": 31
    },
    "2": {
      "name": "Skolmr",
      "class": "druid",
      "level": 85,
    }
  },
  "chris characters": {
    "0": {
      "name": "Trygve",
      "class": "bard",
      "level": 28
    },
    "1": {
      "name": "Brusi",
      "class": "rogue",
      "level": 10
    },
    "2": {
      "name": "Steini",
      "class": "skald",
      "level": 58
    }
  }
}


Mark Meyer :

As it is, your data is a little odd. You have and object with numeric keys, which suggests it should be an array. Having said that you can still search through the Object.values to get the data you want.

let data = {"olis characters": {"0": {"name": "Farah","class": "rogue","level": 74},"1": {"name": "Grop","class": "paladin","level": 31},"2": {"name": "Skolmr","class": "druid","level": 85,}},"chris characters": {"0": {"name": "Trygve","class": "bard","level": 28},"1": {"name": "Brusi","class": "rogue","level": 10},"2": {"name": "Steini","class": "skald","level": 58}}}


function findChar(name, data) {
  for (let charGroup of Object.values(data)) {
    let found = Object.values(charGroup).find(char => char.name === name)
    if (found) return found
  }
}

console.log(findChar('Grop', data))
console.log(findChar('Brusi', data))

// will return undefined if the name is not there:
console.log(findChar('Mark', data))

If you changed the data model to a simple array like:

let data = {
    "olis characters": [{
        "name": "Farah",
        "class": "rogue",
        "level": 74
      },
      {
        "name": "Grop",
        "class": "paladin",
        "level": 31
      }
    ],
    "chris characters": [{
        "name": "Trygve",
        "class": "bard",
        "level": 28
      },
      // ...
    ]
 }

...you could avoid one of those Object.values and use find directly.

function findChar(name, data){
   for (let charGroup of Object.values(data)){
      let found = charGroup.find(char => char.name === name)
      if (found) return found
   }
 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=34460&siteId=1