有没有办法使用 Nunjucks 过滤器提取属性?

Is there a way to extract an attribute using a Nunjucks filter?

是否可以通过使用 Nunjucks 过滤器从每个元素中提取特定属性来映射数组?

我想做类似下面的事情,但我不知道如何使用内置的 Nunjucks 操作。

输入

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

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

输出

green,purple,red
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);