Click on the array key name taken from the variable

I have an array:

var pages = new Array(); 

I want my sheet data to be transferred to this array as follows:

 $('li.page').each(function () { var datatype = $(this).attr('data-type'); var info = $(this).attr('data-info'); pages_order.push({datatype:info}); }); 

but this code does not replace datatype as a variable, just puts the data type string as a key. How do I put the actual string value there as a key name?

+4
source share
5 answers

Finally I saw what you were trying to do:

 var pages = new Array(); $('li.page').each(function () { var datatype = $(this).attr('data-type'); var info = $(this).attr('data-info'); var temp = {}; temp[datatype] = info; pages_order.push(temp); }); 
+9
source
 $('li.page').each(function () { //get type and info, then setup an object to push onto the array var datatype = $(this).attr('data-type'), info = $(this).attr('data-info'), obj = {}; //now set the index and the value for the object obj[datatype] = info; pages_order.push(obj); }); 

Note that you can put a comma between variable declarations rather than reusing the var keyword.

+2
source

It looks like you just want to save two pieces of information for each page. You can do this by clicking an array instead of an object:

 pages_order.push([datatype, info]); 
+1
source

You must use datatype in the context where it will be evaluated.

Same.

 var pages = []; $('li.page').each(function () { var datatype = $(this).attr('data-type'), info = $(this).attr('data-info'), record = {}; record[datatype] = info; pages_order.push(record); }); 

You need only one var , it can be followed by several assignments, separated by a symbol,.

No need to use new Array , just use an array literal []

+1
source

You can add below one line to press a value with the key:

 pages_order.yourkey = value; 
0
source

Source: https://habr.com/ru/post/1401898/


All Articles