我有一个哈巴狗模板,可从Node / mongo / express接收对象数组。基于一个字段的最大值(不是长度),我需要限制html表中的某些列。
例如,从节点渲染的对象可能看起来像这样
{
quantity: 4,
years: 6
},
{
quantity: 78,
years: 2
}
然后,我需要将表中的'year'列数限制为6。我不确定执行此操作的最佳方法,是否在节点中呈现附加的'max'变量,是否可以在哈巴狗中做到这一点,或者如果我应该使用一些客户端js。在(非常)伪代码中,我想要这样的东西...
forEach(Math.max(project.output.years)){
...create an html table 'year' column
}
我不确定pug是否是执行这种数据操作的正确工具。
从nodejs端,您可以使用化简器来查找最大年份值,并将其与其余数据一起发送。
const data = [{
quantity: 4,
years: 6,
},
{
quantity: 78,
years: 2,
},
]
const maxYears = data.reduce((acc, current) => current.years >= acc ? current.years + acc : acc, 0)
console.log(maxYears) // 6
或者使减速器在访问哪个字段进行比较方面更具灵活性。
const data = [{
quantity: 4,
years: 6,
},
{
quantity: 78,
years: 2,
},
]
const findMaxVal = (property, data) =>
data.reduce(
(accumulator, current) =>
current[property] > accumulator ? current[property] : accumulator,
0
)
console.log(findMaxVal("years", data)) // 6
有很多找到最大值的方法,但是最简单的是:
var maxYears = 0;
for(var i = 0 ; i < data.length ; i++){
if( data[i].years > maxYears ){
maxYears = data[i].years;
}
}
(我假设您拥有所有这些对象的数组称为data
)
然后您可以将maxYears传递到哈巴狗模板并执行以下操作:
table
tr
- var col = 0;
while col < maxYears
td(colIndex= col++)
这将产生一个类似于maxYears = 3
的表:
<table>
<tr>
<td colIndex='0'></td>
<td colIndex='1'></td>
<td colIndex='2'></td>
</tr>
</table>
只需为每一行重复该循环。