Home > Blockchain >  Javascript to check dynamic key from object from variable
Javascript to check dynamic key from object from variable

Time:12-20

I have a object array example:

x[1].person.movie
x[3].hobbie.surf

I want to store this in variable and check if this exist before try to get value to avoid the script get undefined error.

How can I store it in variable and check if object array exist: I think the code should be something like that:

let var_check = `x[1].person.movie`;

if(var_check !== "undefined") { alert('safe to store'; }

But this code has error, because it does not check object array value.

CodePudding user response:

You can use optional chaining.

let value = x?.[1]?.person?.movie; // undefined if value could not be accessed

CodePudding user response:

This works if the array is populated correctly, and if you remove the tick marks from the var_check val

const x = [ {}, { person: { movie: 'mov1'}, }, {}, { hobbie: { surf: 'mov2'} }];

let var_check = x[1].person.movie;
if(var_check !== "undefined") { 
  console.log(var_check, 'safe to store'); 
}

  • Related