从 JS 对象的 属性 添加 HTML 数据列表选项

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

<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>

如何仅将每个对象的 属性(在本例中为 CITY)作为选项添加到数据列表?我似乎只添加了整个对象,我只想 select 其中的 CITY 属性。

在您的 forEach 函数中,您引用了作为整个对象的城市,请尝试执行以下操作:

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