Home > Net >  expected an identifier and instead saw an expression
expected an identifier and instead saw an expression

Time:11-04

Hi,

I have this code:

obj = {"ignoredid":"3329"},{"ignoredid":"19693"};
hit = "3329";
if (Object.values(obj).indexOf(hit) > -1) {
   console.log('has it');
} else {console.log('doesnt');}

but I get a warning that says: expected an identifier and instead saw an expression

Why is that? This is the fiddle

https://jsfiddle.net/o7u5L90h/1/

the code works fine on the fiddle despite the warning but not on my actual project (there it will always output "doesnt" no matter what) so I wonder if it will work once I get rid of the warning. What am I missing here?

Thank you.

CodePudding user response:

Maybe you want array of objects? Then you can do something like this

// Helper function to check array of objects
const hasIt = (obj, val) => {
  for(const v of obj) if(v['ignoredid'] === val) return true;
  return false;
}

// Define array of objects
const obj = [{"ignoredid":"3329"},{"ignoredid":"19693"}];

// Test it
if(hasIt(obj, "3329")) console.log('has it');
else console.log('doesnt');
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Or with more recent approach

// Define array of objects
const obj = [{"ignoredid":"3329"},{"ignoredid":"19693"}];

// Test it
if(obj.find(o => o.ignoredid === '3329')) console.log('has it');
else console.log('doesnt');
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

To answer your real question, what is happening there is that the statement obj = {ignoredid : 3329},{ignoredid : 19693}; does not cause a syntax error but does not do what you expect it to do.

Though it's not clear what you expected to happen

  • Related