Click on javascript array if it exists and then don't create it first

Is there a way for this line to always work, rather than throwing TypeError: Cannot read property 'Whatever' of undefined

 var MyArray = []; MyArray[StringVariableName][StringVariableName2].push("whatever"); 
+6
source share
5 answers

Try the following:

 var MyArray = []; MyArray[StringVariableName] = MyArray[StringVariableName] || []; MyArray[StringVariableName][StringVariableName2] = MyArray[StringVariableName][StringVariableName2] || []; MyArray[StringVariableName][StringVariableName2].push("whatever"); 
+11
source

I think, instead of using the array first, use an object if your keys are not integers. There is also an object in the Javascript array. So this is not so.

 var a = []; a['key'] = 'something'; console.log(a); //Gives [] 

I think this is conceptually wrong . Therefore, instead of using Array to store such a pair of data, you should use objects. See this:

 var myObject = myObject || {}; myObject[str1] = myObject[str1] || {}; myObject[str1][str2] = myObject[str][str2] || []; // Now myObject[str1][str2] is an array. Do your original operation myObject[str1][str2].push("whatever"); 
0
source

You can use the literal syntax to configure as if you were using them:

 var myObj = { StringVariableName: { StringVariableName2: [] } }; myObj.StringVariableName.StringVariableName2.push("whatever"); 
0
source

To check without receiving an error:

this snippet allows you to check if a chained object exists.

 var x; try{x=MyArray[name1][name2][name3][name4]}catch(e){} !x||(x.push('whatever')); 

of

fooobar.com/questions/1682 / ...

Reducing javascript object chaining

this function allows you to create chains with a simple string.

 function def(a,b,c,d){ c=b.split('.'); d=c.shift();//add *1 for arrays a[d]||(a[d]={});//[] for arrays !(c.length>0)||def(a[d],c.join('.')); } 

Using

 var MyArray={};//[] def(MyArray,'name1.name2.name3.name4');//name1+'.'+name2.... 

of

fooobar.com/questions/964207 / ...

both work also for arrays with simple change.replace {} with []

If you have questions, just ask.

0
source

You can even do this with expressions using a single-line interface.

 (MyArray[StringVariableName][StringVariableName2] || (MyArray[StringVariableName][StringVariableName2] = [])).push("whatever"); 
0
source

All Articles