VueJS2 and Lodash4: How to nest v-for with another v-for in an HTML table?

Viewed 29

I am having trouble getting some computed data to display properly in my HTML table. How can I replace the x placeholder content in the table with the values from my filteredFieldsWithOldValues() method?

Let me explain.

I have some data like so:

Codesandbox working demo: https://codesandbox.io/s/country-old-and-new-forked-s4zh7?file=/src/App.vue:51-599

{
  "name": "Canada",
  "entryType": 2,
  "shortName": "CanadaEH",
  "shortName_old": "Canada",
  "fullName": "The NEW Republic of Canada",
  "fullName_old": "The Republic of Canada",
  "entryNotes": "Changed the short name and full name ",
  "entryNotes_old": "fixed typo on short name"
}

Using lodash, I am filtering out fields that have the string _old appended to them and also filtering out some additional fields I do not want to show in the data. Overall, it looks like this:

filteredFieldsWithNewValues() {
      const fieldsWithNoOldString = omitBy(this.country, (v, k) =>
        k.endsWith("_old")
      );
      const omittedFields = omit(fieldsWithNoOldString, [
        "updateStatus",
        "entryType",
        "name",
      ]);
      return omittedFields;
    },

This works fine and my data is displaying properly in the HTML table:

enter image description here

However, I need to replace the x placeholder in the table with the values from the keys that have _old appended to them. I tried to do it like so:

    filteredFieldsWithOldValues() {
      const fieldsWithOld = pickBy(this.country, (v, k) => k.endsWith("_old"));
      return fieldsWithOld;
    },

And then in my HTML table I put another v-for on the <tr>'s element like so:

<td v-for="(x, index) in filteredFieldsWithOldValues" :key="index">
{{ x }}
</td>

So, the updated HTML looks like so:

    <table class="table">
      <thead>
        <tr>
          <th scope="col">Field</th>
          <th scope="col">Old</th>
          <th scope="col">New</th>
        </tr>
      </thead>
      <tbody>
        <tr
          v-for="(value, field, index) in filteredFieldsWithNewValues"
          :key="index"
        >
          <th scope="row">{{ field }}</th>
          <td v-for="(x, index) in filteredFieldsWithOldValues" :key="index">
            {{ x }}
          </td>
          <td>{{ value }}</td>
        </tr>
      </tbody>
    </table>

But now, the table is not displaying the values correctly.

How can I correctly show the values from the keys with _old correctly?

1 Answers

Try this

<table class="table">
  <thead>
  <tr>
    <th scope="col">Field</th>
    <th scope="col">Old</th>
    <th scope="col">New</th>
  </tr>
  </thead>
  <tbody>
  <tr
    v-for="(value, field, index) in filteredFieldsWithNewValues"
    :key="index"
  >
    <th scope="row">{{ field }}</th>
    <td>{{ filteredFieldsWithOldValues[field + '_old'] }}</td>
    <td>{{ value }}</td>
  </tr>
  </tbody>
</table>
Related