0

I am stuck at a point where I want to delete a key-value pair from json object in nunjucks template variable.

I have an object: var json = {"id": "123", "obj": {"id": "456", "name": "testing"}, "name":"test", "template": "{% set object = json.obj %}{{object}}"}

In this I am getting entire object without modification. So how can I achieve this in nunjucks template variable?

lxg
  • 12,375
  • 12
  • 51
  • 73
  • What do you want to delete? oh the `name`? – michelem Sep 15 '17 at 08:01
  • @Michelem I tried your solution but still not able to get expected value, I update the object as per my requirement. Is there way to either delete or add any key into json object within nunjucks template variable? – Vikas Sharma Sep 15 '17 at 09:37
  • What exactly do you want to delete? Be more specific – Dushyant Bangal Sep 15 '17 at 09:43
  • Do you want to delete something before or after rendering? – Dushyant Bangal Sep 15 '17 at 09:43
  • @DushyantBangal I want to delete before rendering. – Vikas Sharma Sep 15 '17 at 09:50
  • for any json variable, you can just use `delete myObject.keyName` and it will be deleted. You could just do that before rendering. – Dushyant Bangal Sep 15 '17 at 10:05
  • @DushyantBangal I want to delete during assign it like `"template": "{% set object = json.obj %}{{delete object.name}}{{object}}` and then print the entire object and expected `name` key will not be appear because it should deleted, but its not working as I am expecting and exist `name` key still – Vikas Sharma Sep 15 '17 at 10:15
  • Let me get at this from a different angle. Nunjucks does not exist in a vacuum. Depending what are you using to compile the templates, you should "massage" the data there. For example, Gulp has amazing `gulp-data` which you can load your environment variables (and modify them too). Same should apply for Jinja environments on Python for example. I think you are approaching this at a wrong place. Data should be fed into Nunjucks already prepared, you should just do actions upon it, not radically change the data like deletion etc. – revelt Oct 15 '17 at 21:52

1 Answers1

0

I think you can set it as null or undefined:

{% set obj.name = null %}
michelem
  • 14,430
  • 5
  • 50
  • 66