简体   繁体   中英

Find value of an object in json, node.js

I need a way to find the kills and deaths (etc.) of the corresponding name that is inputted, and if the name is not in the object I need it to output something too.

Something like this:

if (medic does not have(name)) return;
const kills = medic.(name).kills

Sample JSON:

{
  "assault": {
    "general": {
      "kills": 1134,
      "deaths": 1122,
      "abc": "123"
    },
    "list": {
      "A": {
        "name": "name1",
        "kills": 12,
        "deaths": 120
      },
      "B": {
        "name": "name2",
        "kills": 23,
        "deaths": 53
      }
    }
  },
  "support": {
    "general": {
      "kills": 123,
      "deaths": 11232,
      "abc": "11233"
    },
    "list": {
      "A": {
        "name": "name4",
        "kills": 12,
        "deaths": 120
      },
      "B": {
        "name": "name5",
        "kills": 23,
        "deaths": 53
      }
    }
  }
}

First clean your data to get a nice list of the names and info:

const listOfNames = [...Object.values(data.assault.list), ...Object.values(data.support.list)]

Then use the find method on that list to search for a name, with the backup of "Not Found" if the search returns undefined :

const search = (name) => listOfNames.find(item => item.name===name) || "Not Found"

Then you can use that search function elsewhere:

console.log(search("name2")) gives 输出截图

See it in action here: https://repl.it/@LukeStorry/62916291

Do you need assault and support to be sum up or all you need is one of those? Is your data always on the same shape? I'm going to assume that it is, and I'll provide both, the sum and the individual one:

const data = // your JSON here
const getAssaultKills = name => (data.assault.list[name] || {kills: 0}).kills
const getSupportKills = name => (data.support.list[name] || {kills: 0}).kills
const getTotalKills = name => 
  getSupportKills(name) + getAssaultKills(name)

getTotalKills("A") // => 24
getTotalKills("C") // => 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM