1

I have a function that returns an array, how do I define the name of one of the columns in the return array with an argument?

Let's say instead of field 'qty' I want to have field whose name is passed in myFieldName argument.

var results = _.map(
    _.where(data, {
        UNDERLYING: product
    }),
    function (r) {
        if (r["QUANTITY"] != 0 && !isInArray(Date.parse(r["REPORT_DATE"]), errorDates)) {
            return {
                dt: Date.parse(r["REPORT_DATE"]),
                qty: (r["QUANTITY"] * multiplier)
            };
        }
    }
);
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
LucasSeveryn
  • 5,984
  • 8
  • 38
  • 65
  • 1
    just do `r[myFieldName]`? – Daniel A. White May 06 '15 at 13:50
  • Closely related: [Dynamically access object property using variable](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – apsillers May 06 '15 at 13:56
  • Most closely a duplicate of [Using a variable for a key in a JavaScript object literal](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – apsillers May 06 '15 at 13:59
  • As you can see I am already using that notation, the issue is I can't refer to r, as the new array is not r, I can't write r["qty"] instead of qty: – LucasSeveryn May 06 '15 at 14:07

2 Answers2

2

You cannot use the variable name to define a property in an Object literal. So, you may have to create an object and add properties to it, like this

var obj = {};
obj["dt"] = Date.parse(r["REPORT_DATE"]);
obj[myFieldName] = r["QUANTITY"] * multiplier;
return obj;

If you know few of the properties which are going to be there already, then you can define them in the object literal itself, like this

var obj = {
    dt: Date.parse(r["REPORT_DATE"])
};
obj[myFieldName] = r["QUANTITY"] * multiplier;
return obj;

If you are in an environment which supports ECMAScript-6's Computed Property names, then you can simply do

return {
    dt: Date.parse(r["REPORT_DATE"]),
    [myFieldName] : r["QUANTITY"] * multiplier
}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

You can assign properties, new or existing, after creating an object like so:

let foo = {bar: 1};
foo.baz = 2;

To do that with a dynamic name, you need to use the brackets accessor, like:

function assign(obj, field, value) {
    obj[field] = value;
}

In your case, you would do something like:

function getQuantity(data, field) {
  var results = _.map(
    _.where(data, {
      UNDERLYING: product
    }),
    function(r) {
      if (r["QUANTITY"] != 0 && !isInArray(Date.parse(r["REPORT_DATE"]), errorDates)) {
        var returnValue = {
          dt: Date.parse(r["REPORT_DATE"])
        };
        returnValue[field] = r["QUANTITY"] * multiplier;
        return returnValue;
      }
    }
  );
  return results;
}
ssube
  • 47,010
  • 7
  • 103
  • 140