1

I have a map function and would like to pass in a variable as a Key such that the obj.item below takes the variable Salary to become Salary as the key instead of item.

weeklyData.map(function(obj) {
        var day = obj.day;
        var item = "Salary";
        if (day === "Day") {
          obj.item = "text"; // obj.item should be Salary as key
          obj = obj;
        };
        return obj;
      });
Olli
  • 482
  • 2
  • 6
  • 21

2 Answers2

3

Just use bracket notation

obj[item] = "text";

This will set the key to whatever item holds, in your case Salary.

baao
  • 67,185
  • 15
  • 124
  • 181
1

Try the following:

weeklyData.map(function(obj) {
        var day = obj.day;
        var item = "Salary";
        if (day === "Day") {
          obj[item] = "text";
        };
        return obj;
});

You don't need this line obj = obj;, you are working with the object reference.

Andrés Andrade
  • 2,125
  • 2
  • 15
  • 21