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
  • 512
  • 3
  • 6
  • 22

2 Answers2

3

Just use bracket notation

obj[item] = "text";

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

baao
  • 71,625
  • 17
  • 143
  • 203
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,213
  • 2
  • 18
  • 23