2

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
      }
    }
  }
}
3
  • 1
    So you'd input a name like "name4", and it would search through both the assault and support objects, go into their list field, and search those? Commented Jul 15, 2020 at 13:45
  • Please show what you have tried, and any research you have done into solving this for yourself. Commented Jul 15, 2020 at 13:50
  • Loop over Object.keys( ... ) or another array with .includes(), .find() or .filter() to check if the name exists. Commented Jul 15, 2020 at 13:54

2 Answers 2

1

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 screenshot of output

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.