javascript - Dynamic key names -


this question has answer here:

i trying generate object elements dynamically loop passing integer in initial i.e common prefix of elements.

like this:

           if(inventory.inventory_obj.length){                 obj.inventory_length = inventory.inventory_obj.length;                 for(var x=0; x < inventory.inventory_obj.length; x++){                      obj.warehouse_+x = inventory.inventory_obj[x].warehouse;                     obj.name_+x = inventory.inventory_obj[x].name;                     obj.space_+x = inventory.inventory_obj[x].space;                     obj.cost_+x = inventory.inventory_obj[x].cost;                     obj.quantity_+x = inventory.inventory_obj[x].quantity;                     obj.level_+x = inventory.inventory_obj[x].level;                     obj.status_+x = inventory.inventory_obj[x].status;                     obj.deleted_+x = inventory.inventory_obj[x].deleted;                 }             } 

doing above "invalid left-hand side in assignment" error

i have tested inventory.inventory_obj through console.log(inventory.inventory_obj) , verified has needed values.

other tries have made include

                    obj.warehouse_+""+x = inventory.inventory_obj[x].warehouse;                     obj.warehouse+"_"+x = inventory.inventory_obj[x].warehouse;                     obj.warehouse_+x.tostring() = inventory.inventory_obj[x].warehouse;                     obj.warehouse.concat("_"+x+"") = inventory.inventory_obj[x].warehouse;                     //eliminating underscore                     obj.warehouse+x = inventory.inventory_obj[x].warehouse; 

all above failed.

please me understand doing wrong.

to create property name dynamically, use square bracket notation:

obj['warehouse_' + x] = nventory.inventory_obj[x].warehouse; 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -