Home > Net >  Add HTML datalist options from the property of an object in JS
Add HTML datalist options from the property of an object in JS

Time:04-16

<datalist id="city-list">
</datalist>

<script>
let list = document.getElementById('city-list');

const cities = [
    {
        id: 0,
        city: "Buenos Aires",
        country: "Argentina",
        codeIATA: "AEP",
        aeroName: "Aeroparque Internacional Jorge Newbery",
        coordX: -58.370277777778,
        coordY: -34.575,
    },
    {
        id: 1,
        city: "Bariloche",
        country: "Argentina",
        codeIATA: "BRC",
        aeroName: "Aeropuerto Internacional Teniente Luis Candelaria",
        coordX: -71.166666666667,
        coordY: -41.133333333333,
    },

    {
        id: 2,
        city: "Córdoba",
        country: "Argentina",
        codeIATA: "COR",
        aeroName: "Aeropuerto Internacional Ingeniero Ambrosio Taravella",
        coordX: -64.216666666667,
        coordY: -31.316666666667,
    },
];

cities.forEach(function(city){
    let option = document.createElement('option');
    option.value = city;
    list.appendChild(option);
});
</script>

How to add as an option to the datalist only the property (in this case CITY) of each object? I only seem to be adding the entire object, I want to select only the CITY property of them.

CodePudding user response:

In your forEach function you reference city which is the entire object, try doing the following:

cities.forEach(function(city){
let option = document.createElement('option');
option.value = city.city; //reference the city part of your object
list.appendChild(option);
});
  • Related