gpt4 book ai didi

javascript - dust js循环遍历json中的对象

转载 作者:行者123 更新时间:2023-11-29 19:44:10 24 4
gpt4 key购买 nike

我在使用 dust.js 循环遍历 json 时遇到问题,这是我的 json

{
"Undergraduate":{
"metaid":"0770",
"Offcampus":{
"FeesItems":{
"tuition":{
"label":"Tuition Fees",
"value":"5,870"
},
"comprehensive":{
"label":"Comprehensive Fees",
"value":"2,141"
},
"studentActivity":{
"label":"Student Activity Fees",
"value":"190"
},
"academicExcellence":{
"label":"Academic Excellence Fee",
"value":"225"
},
"room":{
"label":"Room",
"value":"0"
},
"board":{
"label":"Board",
"value":"0"
},
"livingAllowance":{
"label":"Living Allowance",
"value":"9,738"
}
}
}
}
}

我想遍历 FeesItems 对象中的项目..

{#Undergradaute.Offcampus.FeesItems}
{label}, {value}{~n} <!-- What should be given in this line? -->
{/Undergradaute.Offcampus.FeesItems}

最佳答案

只要 FeesItems 是一个数组 FeesItems= []

http://akdubya.github.io/dustjs/#guide

{
"Undergraduate":{
"metaid":"0770",
"Offcampus":{
"FeesItems":[{
"label":"Tuition Fees",
"value":"5,870"
},
{
"label":"Comprehensive Fees",
"value":"2,141"
},
...
]
}
}
}
}

这是灰尘指南的示例:

{#friends}
{name}, {age}{~n}
{/friends}

{
friends: [
{ name: "Moe", age: 37 },
{ name: "Larry", age: 39 },
{ name: "Curly", age: 35 }
]
}

更新 1:

由于您不想更改原始 JSON,因此您需要从原始 JSON 生成一个新对象,例如

var newModel =  Object.keys(obj.Undergraduate.Offcampus.FeesItems).map(function(prop){ return obj.Undergraduate.Offcampus.FeesItems[prop] });

请注意,javascript 将保留对对象的引用,如果尝试类似这样的操作:

originalObj.Undergraduate.Offcampus.FeesItems.board.label = "Costa Rica"
console.log(newModel[5].label);

关于javascript - dust js循环遍历json中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21049373/

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