javascript - 我将如何遍历这个数组并基于正则表达式呈现一个表?
问题描述
我正在构建一个 chrome 扩展,它可以获取成分表并将其与数据集进行比较。由于大多数营养表都有一个“营养”类名,因此我通过它们的类名来获取。这就是我得到的:
["\tPer 100g\tPer 35g Ball\nEnergy\t449kcal\t157kcal\nFat\t24.4g\t8.6g\nSaturated fat\t4.5g\t1.6g\nMonounsaturated fat\t13.6g\t4.8g\nPolyunsaturated fat\t5.2g\t1.8g\nTotal Carbohydrates\t31.0g\t10.9g\nSugars\t19.7g\t6.9g\nFibre\t6.1g\t2.1g\nProtein\t23.1g\t8.1g\nSalt\t0.71g\t0.25"]
我正在考虑使用正则表达式来拆分剂量(所以单词)和数字?
解决方案
正则表达式对此将是矫枉过正。您可以简单地拆分字符串,然后将它们映射为更适合您使用的格式。
const input = "\tPer 100g\tPer 35g Ball\nEnergy\t449kcal\t157kcal\nFat\t24.4g\t8.6g\nSaturated fat\t4.5g\t1.6g\nMonounsaturated fat\t13.6g\t4.8g\nPolyunsaturated fat\t5.2g\t1.8g\nTotal Carbohydrates\t31.0g\t10.9g\nSugars\t19.7g\t6.9g\nFibre\t6.1g\t2.1g\nProtein\t23.1g\t8.1g\nSalt\t0.71g\t0.25";
// First, we split the input on each line.
const data = input.split('\n')
// We then skip the first row, since it only contains labels and not data.
.slice(1)
// We then map the individual data rows to objects.
.map(row => {
// We destructure the split array based on the format we expect the data to be in.
const [nutrient, per100, per35] = row.split('\t');
// We bundle the destructured data into a new object and return it.
return { nutrient, per100, per35 };
});
console.log(data);
这会将您的输入整齐地格式化为具有属性和的对象数组nutrient
,然后您可以使用这些对象生成表格的 HTML。per100
per35
推荐阅读
- c++ - 带有 NuGet 的 GLFW OpenGL 无法构建
- knime - 在批处理模式下执行 Knime 时出错:未知选项“-workflow”
- c - 用写函数写数据结构
- spring - Autowired JavaMailSender 上的空指针
- r - networkD3 未绘制预期的交互式网络
- vba - 如果我没有 Internet 连接,如何使用 VBA 在我的 Sharepoint 站点上打开文件?
- android - LiveData postValue 的 Mockito verify() 失败
- ruby - 从字符串和数组的数组创建哈希
- c# - 从我们的服务器运行时收到 NLog 错误,但在本地运行很好
- node.js - 如何在 DialogFlow 中包含输入暂停?