对象数组元素在推送时被修改

时间:2018-08-22 16:27:17

标签: javascript arrays javascript-objects

我有一个空数组

var kpi_arr = [];

我推入一个物体

{
   kpi_id: "18",
   kpi_name: "CSAT",
   kpi_target: "7",
   kpi_months: [
      {
         monthname: "Aug 2017",
         month_value: "",
         month_id: "201",
         month_kpi: "18"
      },
      {
         monthname: "Sep 2017",
         month_value: "",
         month_id: "301",
         month_kpi: "18"
      }
   ]
}

数组现在具有一个具有正确值的对象。但是当我推第二个物体时

{
   kpi_id: "16",
   kpi_name: "Updated handbooks",
   kpi_target: " 100%",
   kpi_months: [
      {
         monthname: "Aug 2017",
         month_value: "",
         month_id: "201",
         month_kpi: "16"
      },
      {
         monthname: "Sep 2017",
         month_value: "",
         month_id: "301",
         month_kpi: "16"
      }
   ]
}

数组内容显示如下

[
{
   kpi_id: "18",
   kpi_name: "CSAT",
   kpi_target: "7",
   kpi_months: [
      {
         monthname: "Aug 2017",
         month_value: "",
         month_id: "201",
         month_kpi: "16"
      },
      {
         monthname: "Sep 2017",
         month_value: "",
         month_id: "301",
         month_kpi: "16"
      }
   ]
},
{
   kpi_id: "16",
   kpi_name: "Updated handbooks",
   kpi_target: " 100%",
   kpi_months: [
      {
         monthname: "Aug 2017",
         month_value: "",
         month_id: "201",
         month_kpi: "16"
      },
      {
         monthname: "Sep 2017",
         month_value: "",
         month_id: "301",
         month_kpi: "16"
      }
   ]
}
]

请注意,所有 month_kpi 属性值均更改为 16 。 这可能是什么原因? 我正在通过以下格式的for循环将这些对象推入数组。

var rolling_months_arr = get_rolling_13month_period();
var kpi_arr = [];

for(){
 var month_kpi = getValueFromWherever();
 var myobject = getObject(rolling_months_arr, month_kpi)
 kpi_arr.push(myobject )
}


//------------------------------------------
function getObject(rolling_months_arr, month_kpi)
{       
    for ( var i = 0; i < rolling_months_arr.length; i++)
    {
        rolling_months_arr[i].month_kpi = month_kpi;
    }

    return rolling_months_arr;
}

function get_rolling_13month_period()
{       
    var month_arr = [];             
    for(){
      month_arr.push({ "monthname": rolling_month,  "month_id": month_id });
      }
    return month_arr;
}

1 个答案:

答案 0 :(得分:1)

rolling_months_arr被重用,您需要在for()内创建一个新的

每次添加到array.push时,您都使用相同的rolling_months_arr,因此在所有实例中值都将更改

var rolling_months_arr = get_rolling_13month_period();放入for()

或克隆该变量: for(){ var month_kpi = getValueFromWherever(); rolling_months_arr = _.cloneDeep(rolling_months_arr); //<= cloneDeep var myobject = getObject(rolling_months_arr, month_kpi) kpi_arr.push(myobject ) }