0

Is there a way of mapping an array by extracting a specific attribute from each element using a Nunjucks filter?

I'd like to do something like the following, but I can't figure out how to do it using the inbuilt Nunjucks operations.

Input

{% set foods = [{name: "apple", colour: "green"}, 
                {name: "plum", colour: "purple"}, 
                {name: "cherry", colour: "red"}] %}

{{ foods | extractattr("colour") }}

Output

green,purple,red
andypea
  • 1,153
  • 7
  • 19
  • Take a Look at [this](https://stackoverflow.com/questions/20990516/loop-through-object-properties-nunjucks) question. – TechySharnav May 12 '21 at 08:28

1 Answers1

2
const nunjucks  = require('nunjucks');
const env = nunjucks.configure();

env.addFilter('map', function (arr, prop, ...etc) {
    var f = typeof prop == 'function' ? prop : typeof this.env.filters[prop] == 'function' ? this.env.filters[prop] : (e) => e[prop]; 
    return arr instanceof Array && arr.map(e => f(e, ...etc)) || arr;
});

const foods = [
    {name: "apple", colour: "green"}, 
    {name: "plum", colour: "purple"}, 
    {name: "cherry", colour: "red"}
];

const html = env.renderString(`{{ foods | map('name') }}`, {foods});
console.log(html);
slideshowp2
  • 38,463
  • 29
  • 127
  • 255
Aikon Mogwai
  • 3,990
  • 2
  • 11
  • 22