如何使用 JavaScript 数组数据填充 SELECT 下拉列表?

Posted

技术标签:

【中文标题】如何使用 JavaScript 数组数据填充 SELECT 下拉列表?【英文标题】:How to populate a SELECT dropdown list with JavaScript array data? 【发布时间】:2021-11-26 06:43:15 【问题描述】:

我是 htmljavascript 的新手。我正在尝试用我的数据文件填充下拉列表并做一个饼图。我的 js 数据如下所示:

const businessData = 
  [  '\ufeffbusiness_id': 'y2gFcAVBXmVxFXAugRe5ig'
    , name               : 'Scrumptious Crumpets'
    , address            : '7414 SE Milwaukie Ave'
    , city               : 'Portland'
    , state              : 'OR'
    , latitude           : '45.47107'
    , longitude          : '-122.64827'
    , stars              : '5'
    , review_count       : '23'
    , is_open            : '0'
    , category           : 'Coffee & Tea'
    , attr_key           : 'restaurantspricerange2'
    , attr_value         : '1'
     

这是我的下拉列表:

// render dropdown
const dropdownElement = document.getElementById("state-dropdown");

// states
let states = [ 
     name: 'OREGON',        abbreviation: 'OR',
     name: 'FLORIDA',       abbreviation: 'FL',
     name: 'OHIO',          abbreviation: 'OH',
     name: 'MASSACHUSETTS', abbreviation: 'MA',
     name: 'TEXAS',         abbreviation: 'TX',
     name: 'COLORADO',      abbreviation: 'CO',
     name: 'GEORGIA',       abbreviation: 'GA',
     name: 'WASHINGTON',    abbreviation: 'WA',
     name: 'MINNESOTA',     abbreviation: 'MN',
    ]

// create dropdown item
// <option value="CA">Open this select menu</option>
states.forEach(function(state) 

    //create the dropdown items
    const optionElement = document.createElement("option");
    //add dropdown value (we will use for code)
    optionElement.value = state.abbreviation
    //create the text that user can read
    const node = document.createTextNode(state.name);
    optionElement.appendChild(node);

    // append to the dropdown select
    dropdownElement.appendChild(optionElement)  
)

我想创建一个下拉菜单,允许我从多个状态中选择数据并绘制来自该状态的数据。到目前为止,我只能通过一次硬编码一个状态来使图表工作。

我怎样才能将数据提取到我的下拉列表中,这样它就可以... 如果选择 CA,则显示 CA 饼图。如果选择 OR,则显示 OR 饼图等...

const californiaStars = businessData.filter(function (obj) 
    return obj.state === 'OR'; 
//Hard coding here in order to get my graph to work for state of OR only
)

let countOfFiveStars = 0
let countOfFourStars = 0
let countOfThreeStars = 0
let countOfTwoStars = 0
let countOfOneStar = 0

californiaStars.forEach(function(obj) 
    switch (obj.stars) 
        case "5":
            countOfFiveStars++;
            break;
        case "4":
            countOfFourStars++;
            break;
        case "3":
            countOfThreeStars++;
            break;
        case "2":
            countOfTwoStars++;
            break;
        case "1":
            countOfOneStar++;
            break;
        default: break;
    
)

console.log(californiaStars)
console.log(countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar)

// 3. put into graph (Pie Chart)
var options = 
    series: [
        countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar
    ],
    chart: 
    width: 700,
    type: 'pie',
  ,
  labels: ['Five stars', 'Four stars', 'Three stars', 'Two stars', 'One star'],
  responsive: [
    breakpoint: 480,
    options: 
      chart: 
        width: 200
      ,
      legend: 
        position: 'bottom'
      
    
  ]
  ;

  var chart = new ApexCharts(document.querySelector("#chart"), options);
  chart.render();

【问题讨论】:

听起来您可能想为 Select 添加一个 onChange 处理程序,并在该更改事件中,将每个选定状态推送到一个可以为您的饼图过滤的数组中。 【参考方案1】:

首先...

const
  dropdownElement = document.getElementById("state-dropdown")
, states = 
  [  name: 'OREGON',        abbreviation: 'OR'  
  ,  name: 'FLORIDA',       abbreviation: 'FL'  
  ,  name: 'OHIO',          abbreviation: 'OH'  
  ,  name: 'MASSACHUSETTS', abbreviation: 'MA'  
  ,  name: 'TEXAS',         abbreviation: 'TX'  
  ,  name: 'COLORADO',      abbreviation: 'CO'  
  ,  name: 'GEORGIA',       abbreviation: 'GA'  
  ,  name: 'WASHINGTON',    abbreviation: 'WA'  
  ,  name: 'MINNESOTA',     abbreviation: 'MN'  
  ]; 


states.forEach((name,abbreviation)=>    // create dropdown items
  
  dropdownElement.add( new Option(name,abbreviation))
  )
dropdownElement.onchange=()=>      // get item clicked when changed
  
  console.log( dropdownElement.value )
  // ... 
  
<select id="state-dropdown">
  <option value="" selected disabled>choose your state...</option>
</select>

【讨论】:

【参考方案2】:

补充答案,您可以创建一个更新图表的函数,如下所示。

在你的 html 中

<select name="states" id="states" onchange="changeState()">
    <option value="OH">Ohio</option>
    <option value="FL">Florida</option>
    <option value="OR">Oregon</option>
    <option value="TX">Texas</option>
</select>
<div id="chart"></div>

然后在你的 script.js 中

// your data
let data = [state: 'OR', stars: '5' ...]

function changeState() 
    // Needed for you to update the chart
    let element = document.getElementById("chart")
    element.remove()
    element = document.createElement('div')
    element.setAttribute('id', 'chart')
    document.body.appendChild(element)

    let state = document.getElementById("states").value;
    // get data by state
    let filter_data = data.filter(d => d.state == state)
    let stars = getStars(filter_data)
    let options = getOptions(stars);

    let chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();



function getStars(filter_data) 
    let countOfFiveStars = 0
    let countOfFourStars = 0
    let countOfThreeStars = 0
    let countOfTwoStars = 0
    let countOfOneStar = 0
    filter_data.forEach(data => 
        switch (data.stars) 
            case "5":
                countOfFiveStars++;
                break;
            case "4":
                countOfFourStars++;
                break;
            case "3":
                countOfThreeStars++;
                break;
            case "2":
                countOfTwoStars++;
                break;
            case "1":
                countOfOneStar++;
                break;
            default: break;
        
    );
    return [countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar]


function getOptions(starts) 
    var options = 
      series: starts,
      chart: 
      width: 380,
      type: 'pie',
    ,
    labels: ['Five stars', 'Four stars', 'Three stars', 'Two stars', 'One star'],
    responsive: [
      breakpoint: 480,
      options: 
        chart: 
          width: 200
        ,
        legend: 
          position: 'bottom'
        
      
    ]

    return options;

【讨论】:

以上是关于如何使用 JavaScript 数组数据填充 SELECT 下拉列表?的主要内容,如果未能解决你的问题,请参考以下文章

我如何用HTML属性填充javascript数组?

javascript 使用数组中的数据填充表

javascript 使用数组中的数据填充表

如何在 JavaScript 中动态填充多维数组?

在 Javascript 文件中使用 jQuery.each() 时,下拉列表中未填充数组中的数据

使用 javascript 和 jquery,用数组结构填充相关的选择框