如何在多维数组中推送值

时间:2019-03-18 15:16:48

标签: jquery arrays push

嗨,

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

我需要这样的东西:

{
    "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>

1 个答案:

答案 0 :(得分: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>