【发布时间】:2016-11-06 18:02:54
【问题描述】:
我想合并 2 个关联数组。当用户按下保存和下一步按钮时,
它应该存储该特定国家的所有数据。 如果country_id 已存在,则应将其所有值替换为用户的最新更新。
window.main_array = []; // all of the data of sub_array will be transferred here.
// when a user clicks a button
// fetch all the input
sub_array = {
'country_id':country_id, // <- should be unique
'countryorigin':countryorigin, // <- should be updated
'marketingbudget':marketingbudget, // <- should be updated
'distributor':distributor, // <- should be updated
'salesrep':salesrep, // <- should be updated
'commission':commission, // <- should be updated
'retainer':retainer, // <- should be updated
'expense':expense, // <- should be updated
'buy_sell':buy_sell, // <- should be updated
'instore':instore, // <- should be updated
'merchandiser':merchandiser, // <- should be updated
'can_sell':can_sell // <- should be updated
};
// the main_array should have a unique country_id, and get the replace the old one with the latest if user updates a value for that country
if(main_array.length <= 0){
// just concat the two arrays if there are no data yet in the main_array
main_array = main_array.concat(sub_array);
}else{
// ???
// should only get the latest input for the selected country'
// replace the old data with the new one
}
// end of click event
【问题讨论】:
-
我有点困惑,也许我没有得到这个问题。根据您的代码,
sub_array是一个对象,main_array是一个空数组,我认为它会包含一些东西?你有一个主数组的例子吗? -
因为 main_array 只是一个容器。 sub_array 的所有数据都将传输到那里。
-
默认情况下 main_array 不应该有任何值,因为它只是一个容器。用户填写表格后,所有用户输入将存储到 sub_array,然后我将它连接到 main_array
-
JavaScript 没有“关联数组”。它有数组,也有对象。你把两者混为一谈了。在您的代码中,
sub_array根本不是一个数组,它是一个对象。我建议从您的问题中删除屏幕截图,因为它无助于澄清任何事情。相反,请列出您希望代码生成的实际输出数据,以及它应该是对象还是数组 - 请阅读 JavaScript 中的输出数据之间的区别。 -
不需要道歉!当您在 PHP 和 JavaScript 等具有相似但不完全相同的特性的语言之间来回切换时,很容易混淆。祝你好运,黑客愉快!
标签: javascript jquery arrays multidimensional-array associative-array