javascript - 创建数组并组合键
问题描述
如何修改项目被推入 jQuery 数组的方式?这是我目前正在使用的代码:
var sub_updated = [];
$('.current-sub-items').each(function() {
$(this).find('.prod-select').each(function() {
if($(this).parent().css('display') != 'none'){
var s_main_prod = $(this).val();
sub_updated.push({
product:s_main_prod,
});
}
});
$(this).find('.var-select').each(function() {
if($(this).parent().css('display') != 'none'){
var s_var_prod = $(this).val();
sub_updated.push({
variation:s_var_prod,
});
}
});
});
console.log(sub_updated);
这输出:
0: {product: "201"}
1: {variation: "202"}
2: {product: "192"}
3: {variation: "194"}
4: {product: "965"}
我怎样才能在下面输出呢?
0: {product: "201", variation: "202"}
1: {product: "192", variation: "194"}
2: {product: "965"}
第 2 行没有变化。
解决方案
你可以试试这个:
var sub_updated = [];
$('.current-sub-items').each(function() {
var obj = {};
$(this).find('.prod-select').each(function() {
if($(this).parent().css('display') != 'none'){
var s_main_prod = $(this).val();
if (s_main_prod ){
obj['product']=s_main_prod
}
}
});
$(this).find('.var-select').each(function() {
if($(this).parent().css('display') != 'none'){
var s_var_prod = $(this).val();
if (s_var_prod ){
obj['variation']=s_var_prod
}
}
});
sub_updated.push(obj);
})
推荐阅读
- python - 为什么在 python for-loop 中计算临时变量会占用这么多内存?
- interface - 使用 SysML/UML 的接口定义和端口类型
- node.js - 错误:SQLITE_ERROR:靠近“READD”:语法错误
- java - 警告:SQL(org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions)错误:1064,SQLState:42000
- ios - NativeScript 中的状态栏样式
- android - android os 的 BroadcastReceiver 什么都不返回
- bash - 初始化某些容器后运行 bash 脚本
- javascript - 从视频标签中删除所有其他“vtt 提示”
- html - 基于 Chrome 的浏览器和其他浏览器上的 fieldset 和 div 之间的不同行为
- java - 无法在 Salesforce 搜索结果中找到元素