skip to Main Content

I have some borrowed code I’m trying to tweak for my needs. Ref. below code:

// Object that will contain all of the MRNs we want to keep
var assgnAuthToKeep = {};

for each(pid3 in PIDsegment['PID.3']) {
  if (pid3['PID.3.4'].toString() in assgnAuthToKeep) {
    delete PIDsegment[pid3.childIndex];
  }
}

How can I check for the value NOT IN the object in the if statement?
!in doesn’t work nor does not in

3

Answers


  1. Like how Rogue mentioned you can invert the boolean expression. Here is your block of code using that method instead:

    var assgnAuthToKeep = {};
    
    for each(pid3 in PIDsegment['PID.3']) {
        let pid3 = PIDsegment['PID.3'][i];
        let pid34Value = pid3['PID.3.4'].toString();
    
        if (!(pid34Value in assgnAuthToKeep)) {
            delete PIDsegment[pid3.childIndex];
        }
    }
    
    Login or Signup to reply.
  2. The !in operator is a valid way to check if a value is not in an object. However, the syntax in your code is incorrect. You need to use the ! operator before the in operator, not after.

    var assgnAuthToKeep = {};
    
    for ( var pid3 in PIDsegment['PID.3'] )
    
    {
        
    if ( ! ( pid3['PID.3.4'].toString() in assgnAuthToKeep ) )
    
     {
           
     delete PIDsegment[pid3.childIndex];
    
        
    }
    
    }
    
    Login or Signup to reply.
  3. I have a few questions:

    • What do your data structures look like?
      • What does PIDsegment look like?
      • Is assgnAuthToKeep a Set, a Map, or an Object?
    • I am not sure what the point of the childIndex is.

    From what I can infer, it looks like you want to use for..of instead of for..in, if you want to access a key on a value.

    // Object that will contain all of the MRNs we want to keep
    var assgnAuthToKeep = new Set(['FOO', 'BAR']);
    
    const PIDsegment = {
      'PID.3': [
        { 'PID.3.4': 'FOO', childIndex: 0 },
        { 'PID.3.4': 'BAR', childIndex: 1 },
        { 'PID.3.4': 'BAZ', childIndex: 2 },
      ]
    };
    
    for (let pid3 of PIDsegment['PID.3']) {
      const assgnAuth = pid3['PID.3.4']?.toString();
      if (assgnAuthToKeep.has(assgnAuth)) continue;
      console.log('Removing:', assgnAuth, pid3.childIndex);
      //delete PIDsegment[pid3.childIndex];
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search