1

I have the following code that works. However, there is a lot of repetition. Here is the code.

            <tr>
                <th>Brand</th>
                <td>{ a_data.brand }</td>
                <td>{ b_data.brand }</td>
                <td>{ c_data.brand }</td>
            </tr>

            <tr>
                <th>Model</th>
                <td>{ a_data.model }</td>
                <td>{ b_data.model }</td>
                <td>{ c_data.model }</td>
            </tr>

            <tr>
                <th>Variant</th>
                <td>{ a_data.variant }</td>
                <td>{ b_data.variant }</td>
                <td>{ c_data.variant }</td>
            </tr>

I have tried to create an array const data = ['a_data', 'b_data', 'c_data']; and loop through that to dynamically display the variables with forEach as well as map. But it does not display anything.

How can I put this in a loop?

1
  • just { data.map(datum => <td>{ datum.variant }</td>) } Commented Jun 12, 2018 at 19:56

2 Answers 2

4

There are many solution to your problem , one and easy solution is

    const a_data = {
    brand:'a',
    model:'aModel',
    variant:'aVariant'
}
const b_data = {
    brand:'b',
    model:'bModel',
    variant:'bVariant'
}
const c_data = {
    brand:'c',
    model:'cModel',
    variant:'cVariant'
}
const data = [a_data,b_data,c_data];
const brands = data.map(brand => (
    <td>{ brand.brand }</td>
));
const models = data.map(brand => (
    <td>{ brand.model }</td>
));
const variants = data.map(brand => (
    <td>{ brand.variant }</td>
));

<tr>
    <th>Brand</th>
    { brands }
</tr>

<tr>
    <th>Model</th>
    { models }
</tr>

<tr>
    <th>Variant</th>
    { variants }
</tr>

as you can see in this solution I use a mock for your objects and add this objects to the array called data .

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

Comments

1

This might be a tad verbose, but you can refactor it if you want. The gist is:

const data = [a_data, b_data, c_data];

const brands = data.map(brand => <td>{ brand.brand }</td>);
const models = data.map(brand => <td>{ brand.model }</td>);
const variants = data.map(brand => <td>{ brand.variant }</td>);

<tr>
    <th>Brand</th>
    { brands }
</tr>

<tr>
    <th>Model</th>
    { models }
</tr>

<tr>
    <th>Variant</th>
    { variants }
</tr>

Comments

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.