gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:16:55 24 4
gpt4 key购买 nike

我有一个空数组

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;
}

最佳答案

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

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

输入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 )
}

关于javascript - 对象数组元素在推送时被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51971298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com