0

I'm struggling with looping through my json feed and finding the matching name, which then upon finding the matching name send back the ID.
For example, if I enter the sport into my UserInput, Soccer. I want to search my JSON feed and find the matching name of Soccer and tell me back the ID

SPORTS.JSON

[{"id":1,"name":"Football"},{"id":2,"name":"Soccer"}]

JAVASCRIPT

function parseSports(data) {
    const sportsIDs = [];
    const JSON = 'https://xxx/sports.json';
    request(JSON , function(err, response, body) {
        if (err) {
            const error = 'cannot connect to the server';
            console.log(error);
        }
        const _data = JSON.parse(body);
        // Get JSON list
        console.log (_data);
        // Split up
        const array = data.split(',');
        // returns input
        console.log (array);
        // Map Sport Name to Sport ID
        array.forEach(name => {
            const find = _data.filter(function(item) {
                return item.name === name;
            });
            if (find && find[0] && find[0].id) {
                sportIDs.push(find[0].id);
            }
        });
        return sportIDs;
    });
}
const userInput = input.substr('6');
if (message.content.endsWith(userInput)) {
    // User Input is Soccer in this example
    const sportIDs= parseSports(userInput);
    // This should tell me the corresponding sport ID for the sport name I entered
    console.log('Sport UserInput', sportIDs);
});
  • Would it be possible for you to make your `sports.json` item be keyed by your `id` instead of having an array of objects? That is, if you did `sports = {"1": "Football", "2": "Soccer"}`, then you could access items by doing `sports[desiredId]` (you could even use an array.) – entersudonym Oct 24 '19 at 20:29
  • that would be awesome! But I can't change the JSON @entersudonym – askmeaquestion1234 Oct 25 '19 at 00:59

0 Answers0