JSON Delete key/value from json and show remaining JSON key/value after refreshing browser

混江龙づ霸主 提交于 2020-06-13 09:15:03

问题


Below are my JSON script and html codes

What i need is if (str="No Coupon") save the state of JSON and delete entire value from it and reload JSON with updated value on browser

/ options.coupon = undefined;
// options = JSON.parse(JSON.stringify(options));
delete options.coupon[3]

I tried with above codes and few other to delete it but the values show after refresh.Could anyone help me to fix it ?

const options = [{
    "country": "First",
    "coupon": ["1", "10", "11"]
  },
  {
    "country": "Second",
    "coupon": "2"
  },
  {
    "country": "third",
    "coupon": "3"
  },
  {
    "country": "fourth",
    "coupon": "4"
  },
  {
    "country": "fifth",
    "coupon": "5"
  }
];

function getRandomValueFromList(list) {
  const randomeIndex = Math.floor(Math.random() * (list.length));
  return list[randomeIndex];
}

$(function() {
  const firstCouponOptions = options[0].coupon;
  options.forEach((value) => {
    $('#sel')
      .append('<option value="' + value.coupon + '">' + value.country + '</option>');
  });

  $('#sel').change(function() {
    let str = $("#sel").val();
    if ($("#sel option:selected").text() === 'First') {
      if (firstCouponOptions.length) {
        str = getRandomValueFromList(firstCouponOptions);
        firstCouponOptions.splice(firstCouponOptions.indexOf(str), 1);
      } else {
        str = "No Coupon";
      }
    }
    console.log(str);
    $("#txtName").val(str);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sel" class="form-control input-lg" data-live-search="true">
  <option value="">-- Select Your Country--</option>
</select>

<input type="text" id="txtName" class="form-control input-lg" />

来源:https://stackoverflow.com/questions/62345580/json-delete-key-value-from-json-and-show-remaining-json-key-value-after-refreshi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!