首页 > 解决方案 > 如何在Angular 8中更新除当前索引之外的对象

问题描述

this.StaticData = {
  "values": [
    {
      "value": "test",
      "label": "test"
    },
    {
      "value": "aa",
      "label": "bb"
    },
    {
      "value": "cc",
      "label": "dd"
    }
  ]
};

我有上述数据对象。我想返回除currentIndex.

例如 -

假设在上述对象中,如果我要编辑0th索引值,并且我已经更新 "value": "rest",而不是"value": "test"并且 "label": "test"需要保持原样。因此,在这种情况下,它将允许更新值。

{
    "value": "rest",
    "label": "test"
},

但是如果我尝试输入"label": "bb"and "label": "dd",那么它将返回false,因为这些值已经在上述对象中可用。

isLabelExist() {
    const formData = this.editStaticParametersForm.value;
    const currentIndex: number = this.StaticData.values.indexOf(this.selectedRowValue);
    if (formData.label_value && this.StaticData) {
      var isPresent = this.StaticData.values.some(function (el) {
        return el.label === formData.label_value
      });
      if (isPresent) {
        return false;
      }
    }
    return true;
  }

标签: javascriptangularangular8

解决方案


使用 find (或一些),您可以检查“索引”(向函数 find 添加第二个参数),所以,

var isPresent = this.StaticData.values.some(function (el,i) {
        return el.label === formData.label_value && i!=currentIndex
      });

真的在 .ts 中,我们使用箭头平面并使用 const 或 let,而不是var

const isPresent = this.StaticData.values.some((el,i)=> {
        return el.label === formData.label_value && i!=currentIndex
      });

或者

const isPresent = this.StaticData.values.some(
    (el,i)=> el.label === formData.label_value && i!=currentIndex);

推荐阅读