我有这个JSON:
"models": [
{
"model": [
{
"hotspotid": "0",
"modelproducts": ["hbeu50282393_406_21","hbeu50286435_404_21","hbeu50286087_279_21"]
},
{
"hotspotid": "2",
"modelproducts": ["hbeu50282393_406_21","hbeu50286435_404_21","hbeu50286087_279_21"]
}
],
"model": [
{
"hotspotid": "0",
"modelproducts": ["hbeu50286435_404_21","hbeu50286087_279_21"]
},
{
"hotspotid": "1",
"modelproducts": ["hbeu50286435_404_21","hbeu50286087_279_21"]
}
]
}
]
我想使用下划线显示每种模式的热点。目前我有这个:
<% _.each( listItem.models, function( model, index ){ %>
<% _.each( model.model, function( hotspot, index ){ %>
<p><%= hotspot.hotspotid %></p>
<% }) %>
<% }) %>
但这仅显示第一个模型的热点ID,我需要做些什么来调整代码以显示两个模型的热点?如果需要,我可以修改JSON和下划线脚本。
答案 0 :(得分:0)
您可以使recursive function
循环以获得所需的深层嵌套属性。
我正在使用underscore mixin
创建recursive function
。这只是一个例子,但您可以根据自己的目的进行修改。
_.mixin({
// pass your json here
recursive: function(obj) {
// your result array of hotspotid
var result = [];
function recurse(val, index, list) {
// if key value is object call this function recursively
if(_.isObject(val)){
_.each(val, recurse);
}
// if you found the key do the desired operation
else if(index=="hotspotid"){
result.push(val);
}
}
recurse(obj);
return result;
}
});
var data = {
"models": [
{
"model1": [
{
"hotspotid": "0",
"modelproducts": [
"hbeu50286435_404_21",
"hbeu50286087_279_21"
]
},
{
"hotspotid": "1",
"modelproducts": [
"hbeu50286435_404_21",
"hbeu50286087_279_21"
]
}
],
"model2": [
{
"hotspotid": "0",
"modelproducts": [
"hbeu50286435_404_21",
"hbeu50286087_279_21"
]
},
{
"hotspotid": "1",
"modelproducts": [
"hbeu50286435_404_21",
"hbeu50286087_279_21"
]
}
]
}
]
};
console.log(_.recursive(data));