jquery - 如何在多维数组中推送值
问题描述
嗨,伙计们,
我需要帮助解决我的麻烦。我想将值推送到特定的数组键中,我做了一些事情,但我推送了很多空值。
我需要这样的东西:
{
"20": {
"0":10,
"1":20,
"2":30
},
"30":{
"0":10,
"1":20,
"2":30
}
}
$("a").click(function() {
pushOrRemove($(this).data('value'), $(this).data('key'))
});
function pushOrRemove(value, array_key) {
var attribute_values = [];
if ($('[data-stored-values]').val().length == 0) {
attribute_values[array_key] = [];
} else {
attribute_values[array_key] = JSON.parse($('#removed_variant_options').val());
}
attribute_values[array_key].push(value);
$('[data-stored-values]').val(JSON.stringify(attribute_values))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-value="10" data-key="20">Click</a>
<a href="#" data-value="20" data-key="20">Click</a>
<a href="#" data-value="30" data-key="20">Click</a>
<a href="#" data-value="10" data-key="30">Click</a>
<a href="#" data-value="20" data-key="30">Click</a>
<a href="#" data-value="30" data-key="30">Click</a>
<input type="text" data-stored-values>
解决方案
$("a").click(function() {
pushOrRemove($(this).data('value'), $(this).data('key'))
});
function pushOrRemove(value, array_key) {
// get the variable you store the json in
var $storedValues = $('[data-stored-values]');
// if the json is not set, default to an empty object
var attribute_values = JSON.parse($storedValues.val() || '{}');
// if the key is not in the object yet, defaultto an empty array
attribute_values[array_key] = attribute_values[array_key] || [];
// get the index of the value
var indexOfValue = attribute_values[array_key].indexOf(value);
// if the index is -1, it's not in there, so add
if (indexOfValue < 0) {
attribute_values[array_key].push(value);
} else {
// the index was 0 or more, so remove it
attribute_values[array_key].splice(indexOfValue, 1);
}
// update the stored json for the next interaction
$storedValues.val(JSON.stringify(attribute_values));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-value="10" data-key="20">Click</a>
<a href="#" data-value="20" data-key="20">Click</a>
<a href="#" data-value="30" data-key="20">Click</a>
<a href="#" data-value="10" data-key="30">Click</a>
<a href="#" data-value="20" data-key="30">Click</a>
<a href="#" data-value="30" data-key="30">Click</a>
<input type="text" data-stored-values>
推荐阅读
- algorithm - 如何计算可能的不同序列的数量?
- vue.js - 有没有办法在fabricjs onclick中增加和减少字体大小
- python - 关于 Scikit-Learn 提前停止的问题
- javascript - 单击按钮时如何刷新/重新加载页面
- javascript - 为什么 webpack 打包时不包含 assert.rejects(UMD 库目标)
- gridview - Yii2:Kartik Gridview - 在数据单元格上方导出带有标题的 excel
- java - 带有 RSQL 的 REST 查询语言用于日期字段
- python - 绘制存储为顶点和面的网格
- javascript - React - 安装/卸载的顺序以及如何实现“责任链”
- c++ - 无法区分 JSON 对象/数组/字符串