首页 > 解决方案 > 我将如何遍历这个数组并基于正则表达式呈现一个表?

问题描述

我正在构建一个 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"]

我需要遍历这个数组并以这种格式返回它: 在此处输入图像描述

我正在考虑使用正则表达式来拆分剂量(所以单词)和数字?

标签: javascriptreactjs

解决方案


正则表达式对此将是矫枉过正。您可以简单地拆分字符串,然后将它们映射为更适合您使用的格式。

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。per100per35


推荐阅读