1

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.

When property value is 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
    }
  }
}
imPK
  • 764
  • 2
  • 7
  • 30

1 Answers1

0

I believe what you are looking for is:

  1. ES6 in operator
  2. 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.

rafaelwalter
  • 136
  • 4