Markcce Eros Markcce Eros - 14 days ago 8
Javascript Question

Javascript get name from data by id function

I need to create a function the would return the name of the car when given the id.

I have this data:

{
"cars": [
{
"id": "661",
"name": "ford"
},

{
"id": "657",
"name": "fiat",
},

{
"id": "654",
"name": "volvo",
},

{
"id": "653",
"name": "porche",
},

{
"id": "650",
"name": "mazda",
}

]
}


So I've done this:

function getCarNameFromId(id) {

theData = {
"cars": [
{
"id": "661",
"name": "ford"
},

{
"id": "657",
"name": "fiat",
},

{
"id": "654",
"name": "volvo",
},

{
"id": "653",
"name": "porche",
},

{
"id": "650",
"name": "mazda",
}

]
};

console.log(theData.name);

}


then call it:

function getCarNameFromId('650');


How do I finish this code so I can get the code to return me the name of the id specified?

Answer

JS solution

var findCar = function(id) {
    var theData = {
        "cars": [{
                "id": "661",
                "name": "ford"
            },

            {
                "id": "657",
                "name": "fiat",
            },

            {
                "id": "654",
                "name": "volvo",
            },

            {
                "id": "653",
                "name": "porche",
            },

            {
                "id": "650",
                "name": "mazda",
            }

        ]
    };

    for (var i = 0; i < theData.cars.length; i++) {
        var car = theData.cars[i];
        if (car.id === id)
            return car.name;
    }
}
console.log(findCar("654"));