0

Im building a chrome extension that grabs a table of ingredients and compares it with a dataset.Since most nutrient table have a classname of "nutrition" im grabbing the via their className. This is what I got:

["\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"]

i need to loop thru this array and return it in this format: enter image description here

I was thinking of using Regex to split out the doses (so words) and numbers?

1 Answer 1

1

Regex would be overkill for this. You can simply split the strings and then map them into a format that's better for you to work with.

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);

This formats your input neatly into an array of objects with properties nutrient, per100 and per35, which you can then use to generate your table's HTML from.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Ian. Im annoyed i didnt figure this out. Im a jr with 6 weeks experience, do you think this was a basic task ?
@ShuibAbdillahi glad I could help. I'd say that transforming input data like this is indeed a basic task, but if you've only just started out with 6 weeks of experience I wouldn't worry too much about not immediately realizing how to do it. Some concepts like slicing, mapping, splitting and the like are best learned through usage, at some point they will appear natural enough to you.
yeah your right, hope you have a great day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.