简体   繁体   English

创建一个数组并执行一个函数

[英]Create an array and execute a function

I'm using Angular 6 and have function which will change the value of a property and also adds the property to an array if the array exists. 我正在使用Angular 6,并且具有将更改属性值的功能,并且还将在数组存在的情况下将该属性添加到数组。

When property value is true 当属性值为true时

{
  "myArray": ["property1"],
  "properties": {
    "property1": {
      "value": true
    },
    "property2": {
      "value": false
    }
  }
}

But when I'm trying to change the value of the property if there is no array present then I get array is undefined error 但是当我尝试更改属性的值(如果不存在数组)时,我得到数组未定义错误

{
  "properties": {
    "property1": {
      "value": false
    },
    "property2": {
      "value": false
    }
  }
}

How can I add back an array and execute the same method which I'm doing when there is an array existing 当存在数组时,如何添加数组并执行与我相同的方法

like 喜欢

{
  "myArray": ["property2"],
  "properties": {
    "property1": {
      "value": false
    },
    "property2": {
      "value": true
    }
  }
}

I believe what you are looking for is: 我相信您正在寻找的是:

  1. ES6 in operator 运营商ES6
  2. Array.isArray() Array.isArray()

So its possible to build something like: 因此,可以构建如下内容:

const data = {
  "properties": {
    "property1": {
      "value": false
    },
    "property2": {
      "value": false
    }
  }
};

// iterate over keys
for (const property in data.properties) {
  // if value is true
  if (data.properties[property].value) {
    if (Array.isArray(data.myArray)) {
       // property is a string (key)
       data.myArray.push(property);
    } else {
      // not an array do something else
    }
  } 
}

There are possible optimizations to it but depends more on the logic you are trying to build. 可以进行优化,但更多取决于您尝试构建的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM