首页 > 解决方案 > 如何根据对象数组中字段的最大值限制 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
}

标签: javascriptnode.jspug

解决方案


我不确定 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


推荐阅读