【问题标题】:How can I get a specific object from an array in javascript? [duplicate]如何从 javascript 中的数组中获取特定对象? [复制]
【发布时间】:2021-08-10 00:46:21
【问题描述】:

我正在尝试在满足特定条件的数组中查找对象。我有一个从 CSV 文件创建的数组,它给出以下结果:

0: {production_company: "Columbia Pictures", Pass: 50, Fail: 65, total: 115}
1: {production_company: "Universal Pictures", Pass: 47, Fail: 65, total: 112}
2: {production_company: "Warner Bros.", Pass: 38, Fail: 74, total: 112}

然后我有一个带有复选框的下拉菜单,我在其中使用 jQuery 选择器和更改处理程序检查哪个被“选中”。到目前为止,我可以获得属性 id。在下面的代码中,我使用了 find 方法:

        var rowConverter_P = function(d) {
                return {
                        production_company: d.production_company,
                        Pass: parseInt(d.Pass),
                        Fail: parseInt(d.Fail)
               
                };
              }

d3.csv(production_dataset_url, rowConverter_P).then(function(data){

d3.selectAll("input").on("change", function(){

               
                        var paragraphID = d3.select(this).attr("id");
                        console.log("paragraph id", paragraphID); //this works
          
                        if($(this).is(":checked")) {
                               

                       var new_data= data.find(d => d.production_company == paragraphID);
                                console.log("new data: ", new_data);}
}});

我的 HTML 代码:

<div class="dropdown-menu">
            <button class="dropdown-item" type="button">
             <input type="checkbox" id="Columbia Pictures" checked> Columbia Pictures
             </button>
            <button class="dropdown-item" type="button">
                <input type="checkbox" id="Universal Pictures" checked> Universal Pictures
            </button>
            <button class="dropdown-item" type="button">
                <input type="checkbox" id="Warner Bros." checked> Warner Bros.
            </button>
</div>

这里的问题是我得到了变量 new_data = Undefined。我想可能是因为我正在比较具有不同数据类型的两个值,所以我将变量paragraphID 转换为字符串,因为我之前将production_company 解析为字符串,但它仍然是未定义的。我在这里错过了什么?

【问题讨论】:

  • 您确定paragraphID 匹配production_company 名称之一吗?尝试控制台记录paragraphID 进行检查
  • 我做到了,它匹配它。
  • 您只想要与已更改复选框关联的数据吗?不是所有的复选框?运行您的代码,否则它似乎对我有用。 $(this).is(":checked") 也可以是 this.checked
  • 我只需要已更改的复选框。我的理解是 on("change, ) 对更改的复选框起作用,即使默认情况下所有复选框都已选中,因此它会获取该特定框的当前状态@AndrewReid

标签: javascript jquery d3.js


【解决方案1】:

我可以通过改变这个变量的位置来解决这个问题:

var new_data= data.find(data => data.production_company == paragraphID);

我曾经在从数组中删除后调用变量。

【讨论】:

  • 您的问题中已经包含此代码。如果它已经存在,你的意思是你用那个代码“解决了这个问题”?
  • 我改变了它的位置
猜你喜欢
  • 2019-08-01
  • 1970-01-01
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
  • 2018-11-05
相关资源
最近更新 更多