javascript - 如何根据对象数组中字段的最大值限制 HTML 列元素
问题描述
我有一个哈巴狗模板,它接收来自 Node/mongo/express 的对象数组。基于一个字段的最大值(不是长度),我需要限制 html 表中的某些列。
例如,从节点渲染的对象可能看起来像这样
{
quantity: 4,
years: 6
},
{
quantity: 78,
years: 2
}
然后我需要将表中的“年份”列数限制为 6。我不确定最好的方法是什么,是否在节点中渲染一个额外的“最大”变量,是否可以这在哈巴狗中,或者我应该使用一些客户端 js。在(非常)伪代码中,我想要这样的东西......
forEach(Math.max(project.output.years)){
...create an html table 'year' column
}
解决方案
我不确定 pug 是否是进行这种数据操作的正确工具。
在 nodejs 方面,您可以使用 reducer 来查找最大年份值并将其与其余数据一起发送。
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
或者让 reducer 在访问哪个字段进行比较方面更加灵活。
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
推荐阅读
- python - 如何更改 Python 请求中的服务器名称指示?
- azure - 如何配置 webhook 活动?
- jenkins - 如何通过 Perforce 上的代码更改自动触发 Jenkins 作业
- javascript - 非线性颜色渐变向量 Javascript
- excel - 从 CSV 中提取值并将其放入 Excel 工作表中
- google-cloud-platform - 访问 Google Cloud Storage 触发事件“Pub/Sub”?
- postgresql - 使用查询 postgresql 在多列中搜索非空条件
- apache-spark - 基于另一个数据框的带有列条件的pyspark
- encryption - Web.config 中重写规则部分的加密
- spring-boot - Redis最大等待和超时之间的区别