Search code examples
javascriptjqueryflot

Can I use parameter to define field name


The following JavaScript code works, but is there a more compact way to write it using n parameter, to "eval" y1axis, y2axis, y3axis field names?

  switch (n) {
    case 1:
      markingsY = [
             { color: colorErr, y1axis: { from: maxVal } },
             { color: colorErr, y1axis: { to: minVal } },
             { color: "#00f", lineWidth: 1, y1axis: { from: minVal, to: minVal } },
             { color: "#00f", lineWidth: 1, y1axis: { from: maxVal, to: maxVal } }
          ];
    break;

    case 2:
      markingsY = [
             { color: colorErr, y2axis: { from: maxVal } },
             { color: colorErr, y2axis: { to: minVal } },
             { color: "#00f", lineWidth: 1, y2axis: { from: minVal, to: minVal } },
             { color: "#00f", lineWidth: 1, y2axis: { from: maxVal, to: maxVal } }
          ];
    break;

    case 3:
      markingsY = [
             { color: colorErr, y3axis: { from: maxVal } },
             { color: colorErr, y3axis: { to: minVal } },
             { color: "#00f", lineWidth: 1, y3axis: { from: minVal, to: minVal } },
             { color: "#00f", lineWidth: 1, y3axis: { from: maxVal, to: maxVal } }
          ];
    break;

    default:
    break;


  }

Solution

  • Edit: Misread the question, Sorry!

    You could use a static key instead of the one you need to change, then change it dynamically, so:

    markingsY = [
        { color: colorErr, yaxis: { from: maxVal } },
        { color: colorErr, yaxis: { to: minVal } },
        { color: "#00f", lineWidth: 1, yaxis: { from: minVal, to: minVal } },
        { color: "#00f", lineWidth: 1, yaxis: { from: maxVal, to: maxVal } }
    ];
    markingsY.forEach(function(item){
        item["y"+n+"axis"]=item.yaxis;//copy it to its new key
        delete item.yaxis;//remove the old one
    });