【问题标题】:How can I push values in multidimensional array如何在多维数组中推送值
【发布时间】:2019-08-09 00:14:14
【问题描述】:

大家好,

我的麻烦需要帮助。 我想将值推送到特定的数组键中,我做了一些事情但我推送了很多 null。

我需要这样的东西:

{
    "20": {
        "0":10,
        "1":20,
        "2":30
    },
    "30":{
        "0":10,
        "1":20,
        "2":30
    }
}

Source here

$("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>

【问题讨论】:

  • 这些都不是数组。它们都是对象。 [] 表示一个数组,{} 是一个对象。
  • 什么是removed_variant_options?!!
  • @ZakariaAcharki 我忘了更改实际上是 $('[data-stored-values]') 隐藏输入

标签: jquery arrays push


【解决方案1】:

$("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>

【讨论】:

    猜你喜欢
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 2021-01-27
    • 2020-01-25
    • 2017-12-30
    相关资源
    最近更新 更多