0

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..i.e. 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

2

1 Answer 1

1

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

function (prod_sku, attr)
        {
            Page.getAttribute(UpdateFieldName).setValue(prod_sku[attr]);
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.