【问题标题】:How do I get the index of object in array using angular?如何使用角度获取数组中对象的索引?
【发布时间】:2020-03-17 03:47:30
【问题描述】:

我需要在数组中有一个对象的索引,这样我才能删除数组的这一部分。我试过用这个:

var index = this.urenRegistratie.indexOf(newDatum);

但它一直返回-1,我不知道为什么会这样。

这是我拥有的代码的一部分。它从 html 中的表单中获取数据并将其放入我的数组中,现在我已经准备好一个 if 语句(exisitingDatum),我的代码需要在那里。有人可以帮帮我吗?

 store(newValue:number, newDatum, newAanwezig, newComment){
    const existingDatum = this.urenRegistratie.find(billable => {
      return billable.datum === newDatum;
      return
    });

    if (!existingDatum) {
        let billable = new BillableHours();
        billable.datum = newDatum;
        billable.hours = +newValue;
        billable.aanwezig = newAanwezig;
        billable.comment = newComment;

        if(billable.aanwezig == "Aanwezig" && billable.hours !== 0 && billable.datum !== null) {
          this.urenRegistratie.push(billable);
        }
    }

    if(existingDatum) {

    }

  }

【问题讨论】:

    标签: javascript arrays angular typescript indexof


    【解决方案1】:

    As mdn says:

    findIndex() 方法返回第一个元素的索引 满足提供的测试功能的数组。否则,它 返回-1,表示没有元素通过测试。

    如果您有这样的对象数组,请尝试使用findIndex

    const a = [
        { firstName: "Adam", LastName: "Howard" },
        { firstName: "Ben", LastName: "Skeet" },
        { firstName: "Joseph", LastName: "Skeet" }
    ];
    
    let index = a.findIndex(x => x.LastName === "Skeet");
    console.log(index);

    【讨论】:

      【解决方案2】:

      补充@StepUp的答案(请选择他的答案,因为它很好地回答了这个问题):

      查找索引与 Angular 无关,而是 Vanilla JavaScript。

      在您的情况下,您需要一个以newDatum“needle”为参数的函数,以便使用findIndex 在数组“haystack”中进行搜索:

      var getNewDatumIndex = (array, newDatumNeedle) => {
        return array.findIndex(x => x.newDatum === newDatumNeedle); 
      }
      

      如果需要,您也可以在数组原型中添加方法,以省略第一个参数:

      Array.prototype.getNewDatumIndex = (newDatumNeedle) => {
        return this.findIndex(x => x.newDatum === newDatumNeedle); 
      }
      

      【讨论】:

        【解决方案3】:

        一个简单而优雅的解决方案是使用_.isEqual,它使用lodash库进行深度比较

        Npm 包 -- https://www.npmjs.com/package/lodash

        const a = [
           { firstName: "Adam", LastName: "Howard" },
           { firstName: "Ben", LastName: "Skeet" },
           { firstName: "Joseph", LastName: "Skeet" }
        ];
        const find =  { firstName: "Joseph", LastName: "Skeet" }
        
        index = a.findIndex(x => _.isEqual(x, find));
        
        console.log(index);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-10-23
          • 1970-01-01
          • 1970-01-01
          • 2012-02-21
          • 1970-01-01
          • 2018-04-25
          • 2014-11-30
          • 1970-01-01
          相关资源
          最近更新 更多