Search code examples
javascriptpythonjsonautocompletematerialize

Append javascript dictionary to other dictionary


I am creating an app with materialize css. Materialize css has an autocomplete js feature. You can pass in data to autocomplete. I also have a python flask backend that returns a python dictionary in JSON form. Javascript receives it on the front end and parses the JSON data. I was wondering if it would be possible to append the JSON data into the premade autocomplete. Here is my code:

<script>
  //parse json data
  var datas = JSON.parse('{{ data | tojson | safe}}');
  console.log(datas)
  console.log(datas['Nick'])

    $('input.autocomplete').autocomplete({
          data: {
            'Apple': null,
            datas: null
          }
        });
    </script>

My console looks like this, so I know I have a useable python dictionary:

{Nick: "null", User: "null"}
    Nick: "null"
    User: "null"
    __proto__: Object
null

I have tried using my data directly, passing it in through the data field instead of data: but I have no luck. I would like to use my JSON data in the data field of the autocomplete, how would I do this? Thank you!


Solution

  • To append your objects you can do, something like:

    <script>
      var datas = JSON.parse('{{ data | tojson | safe}}');
      var newData = $.extend({'Apple':null}, datas);
    
      $('input.autocomplete').autocomplete({
          data: newData
      });
    </script>