简体   繁体   中英

Translate string name into object by same name

First my title may not be a very good one so I will gladly update it with any suggestions.

So my desire was to implement DRY on some javascript code. In essence there were three functions (more to come) that were exactly the same except for one part of one line. So my thought was to modularize it and in a loop exec the one line.

So the line of code BEFORE any changes would have looked like this in the three different functions:

...snip
function (prod_sku)
        {
            Page.getAttribute(UpdateFieldName).setValue(prod_sku.ProductName));
        },


...snip 2
function (prod_sku)
        {
            Page.getAttribute(UpdateFieldName).setValue(prod_sku.ProductSKU));
        },

...snip 3
function (prod_sku)
        {
            Page.getAttribute(UpdateFieldName).setValue(prod_sku.ProductQty));
        },

So as you can see the only diff is ProductName, ProductSKU, ProductQty.

So my thought was to have one call where the fields to update were passed in then split into an array.

passed in as 'ProductName,ProductSKU,ProductQty,...' (UpdateFieldValue is the parm variable)

split into an array as var arrayUpFldVal = UpdateFieldValue.split(',');

then loop through the array executing the one line with the array val concatenated.

function (prod_sku)
        {
            Page.getAttribute(UpdateFieldName).setValue(prod_sku +'.' + arrayUpFldVal [index]));
        },

only as you probably could predict was coming it translated the object to a string representation to be able to concatenate.

[object Object].ProductNumber

So how do I get my string name to represent an object..ie prod_sku.ProductName

I could do a series of if statements like below but...kinda seemed to defeat the main objective...sure it reduces a lot of repetitive code but I was hoping for a clean solution.

if(arrayUpFldVal == 'ProductName')
{
  Page.getAttribute(UpdateFieldName).setValue(prod_sku.ProductName));
}

So any input would be appreciated

You could rework your function to contain a new "attr" parameter:

function (prod_sku, attr)
        {
            Page.getAttribute(UpdateFieldName).setValue(prod_sku[attr]);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM