0

Following a previous answered question, I'm iterating over keys in JSON and putting them inside <option> tags in a select menu. It works fine, but I want it synchronized so that it's removed automatically if a key is removed from the JSON data.

My JSON data:

{
  "config": {
    "title key1": [
      "hello",
      "hola",
      "mi seudónimo es fivethous"
    ],
    "title key2": [
      "hejsan",
      "tjena"
    ],
    "title key3": [
      "random",
      "hello",
      "good bye"
    ]
  }, 
    "info": [
      "Hello world,",
      "how are you doin?",
      "Its not going to well for me unfortunately."
    ]
}

I have multiple keys iterated, each in it's own function. In this particular function I'm iterating over all the keys inside the parent config key.

var info;
var config;

function json() {
  $.getJSON("/static/_info",
    function(d) {
        info = d.info;
        config = d.config;

    });
}

function tvshows() {
        tvShows = [];
        $('option#show').each(function() {
          tvShows.push($(this).text());
        });

        $.each(config, function(show) {
          if (!tvShows.includes(show)) {
              $('#select_tvshow').prepend('<option id="show" value="' + show + '">' + show + '</option>');
          }
        });
}

function updatelog() {
    -||-
}

function updates() {
    json();
    updatelog();
    tvshows();
}

var interval = window.setInterval(updates, 2000);

Also, it would be great if this applied likewise to values.

I have tried as many different approaches I can think of, how do I accomplish this? Thanks in advance.

Community
  • 1
  • 1
fivethous
  • 79
  • 2
  • 13
  • Could you provide us with your JSON string? – Alex Apr 25 '16 at 23:44
  • Just did @AlexClem – fivethous Apr 25 '16 at 23:45
  • My JSON was not correct at first. It's now corrected. Just a heads up. – fivethous Apr 25 '16 at 23:52
  • Why don't you just remove all the options, then add in the options from the JSON? – Barmar Apr 26 '16 at 00:13
  • What do you mean? If so it would not be automated? – fivethous Apr 26 '16 at 00:18
  • 1
    You can delete all the options and then repopulate them from the JSON using jquery empty method on the container see: string http://api.jquery.com/empty/ After that you just need to repopulate them the same way you first created them. – Alex Apr 26 '16 at 00:39
  • Ah! That's smart, i'll use it. Although, I have trouble updating my `tvShows` array (i.e. removing the item in the array which does not exist in JSON output, so they match). I tried with unsetting/removing the array in a `if` statement but I can't get it to work properly. Can you please explain how to approach this? I think I might have been a little unclear with my precise question, but i'll update with an answer when I have it. – fivethous Apr 26 '16 at 17:05

0 Answers0