gpt4 book ai didi

javascript - Nunjucks 迭代数组中的项目以显示对象中的项目

转载 作者:行者123 更新时间:2023-11-28 15:04:37 24 4
gpt4 key购买 nike

在 javascript 中,我可以循环数组来输出我的对象,如下所示。

var myArr = ["one","two","three"]
var myObj = {
"one": {
"title": "ones",
"desc": "this is one"
},
"three": {
"title": "threes",
"desc": "this is three"
},
"two": {
"title": "twos",
"desc": "this is two"
}
}

myArr.forEach(function (value) {
console.log(myObj[value].title, myObj[value].desc);
});

输出

这是一个

这是两个

三,这是三

console.log("number 2 - ",myObj[myArr[1]].desc)
console.log("number 2 - ",myObj["two"].desc)

输出

数字 2 - 这是两个

数字 2 - 这是两个

我希望能够在nunjucks中执行此操作,因为我想控制myArr的显示顺序,但也希望能够灵活地拥有单个页面,例如one.html,我在其中可以专门针对一个,例如 {{testObj.one.title}}

如何用 Nunjucks 来实现这一点?我已经尝试过以下方法。

-- nunjucks --
<ul>
{% for item in testArr %}
<li>{{item}} - {{testObj.one.title}}</li>
{% endfor %}
</ul>

<ul>
{% for obj, item in testObj %}
<li>{{ obj }}: {{ item | dump }} - {{ item.title }} - {{ item.desc }}</li>
{% endfor %}
</ul>

--- output ---
<ul>
<li>one - ones</li>
<li>two - ones</li>
<li>three - ones</li>
</ul>

<ul>
<li>one: {"title":"ones","desc":"this is one"} - ones - this is one</li>
<li>three: {"title":"threes","desc":"this is three"} - threes - this is three</li>
<li>two: {"title":"twos","desc":"this is two"} - twos - this is two</li>
</ul>

我的理想输出如下所示,我可以根据 myArr 排序显示,但对于每个项目,在 myObj 中显示其键的内容

<ul>
<li>one - ones</li>
<li>two - twos</li>
<li>three - threes</li>
</ul>

最佳答案

<ul>
{% for item in myArr %}
<li>{{item}} - {{myObj[item].title}}</li>
{% endfor %}
</ul>

关于javascript - Nunjucks 迭代数组中的项目以显示对象中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39626312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com