0

I have the following loop which I have put together and is working (up to a point):

 for (var i = 0; i < dataIn.length; i++) {
  if (dataIn.YourName = [] ) {
      var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
      dataIn[i].YourName = modifiedName; 
       
     }
     
    else {
 console.log('Do Nothing');
    }
 }

However, I run into an error when the content from the API source is empty (null). Console error: Cannot read property 'replace' of null

As a result I have tried to update my loop to only run if the information is NOT null or undefined (see below), but it is being ignored and still trying to run.

for (var i = 0; i < dataIn.length; i++) {
  if (dataIn.YourName !== null && dataIn.YourName !== '' ) {
      var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
      dataIn[i].YourName = modifiedName; 
       
     }
     
    else {
 console.log('Do Nothing');
    }
 }

Sample data from the API.

What works:

"YourName": "John Citizen", 

What throws the console error:

"YourName": null, 
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
pixelcreated
  • 188
  • 9
  • 5
    `=` is the assignment operator, you want `==` or `===`. But your `if` condition will still not work as expected because this is not how you check if a variable stores an empty array. – Andreas Mar 30 '21 at 12:14
  • We need to have an idea of how `dataIn` looks like – yunzen Mar 30 '21 at 12:16
  • _"is NOT null or undefined"_ - `'' !== undefined` – Andreas Mar 30 '21 at 12:16
  • Does this answer your question? [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – Heretic Monkey Mar 30 '21 at 12:20

1 Answers1

2

Let's first address an issue here. This line:

if (dataIn.YourName = [] ) {

Will always evaluate true. You are assigning an empty array to your YourName property and then using that assignment in an if - empty arrays are always truthy.

As to how you've tried to correct it, you're checking initially dataIn.YourName but then trying to read dataIn[i].YourName - you need to be consistent. I suspect what you want is:

 if (dataIn[i].YourName !== null && dataIn[i].YourName !== '' ) {
    var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
    dataIn[i].YourName = modifiedName;        
 }
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Thank you Jamiec. Answer is obvious now that you pointed it out. Appreciated the help and the prompt reply. Take care! – pixelcreated Mar 30 '21 at 12:29