Search code examples
javascriptarraysnode.jsnunjucks

Accessing arrays in Nunjucks template within <script>


I have an array on server side, which adds the number 1 every 10 minutes. e.g. [1, 1, 1, 1....]

I send this to the template as follows (data() is the array as my example above):

router.get('/', (req, res) => {
  return res.render('index', {
    results: data(),
  });
});

I have a script on the template which renders a graph. For this to work, the array needs to be accessible in the script.

When I access the array by:

var results = "{{ results }}";

The array ends up like:

["1, 1, 1, 1"]

I need the array without the double quotes. Is this possible?

[1, 1, 1, 1]

Solution

  • You could change it on the server or the client - I'd say let's just do it on the client side.

    The entire array is made up of 1 spot that has all the values separated by commas.
    We first grab that chunk of data with (["1, 1, 1, 1"][0]) - this will return just the first spot in the array with all of the data.

    Then we clear out any spaces (.replace(/\s/g,'').

    Turn it into a true array (split(",")).

    Then turn each of those string numbers into true numbers (.map(function(e){return Number(e);}))

    remove: .map(function(e){return Number(e);}) if you don't care if the numbers are strings or not.

    var results = ["1, 1, 1, 1"][0];
    var result = results.replace(/\s/g,'').split(",").map(function(e){return Number(e);});
    console.log(result);