0

In data, I have 2 arrays. In the template, I want to use value of a special key of an array, to target the second array.

<template>
  <table>
    <tr v-for="sa in mySecondArray">
      <td v-for="fa in myFirstArray">
         {{ ??? }}
      </td>
    </tr>
  </table>
</template>

// ...
data() {
  myFirstArray: [
  {
    a: "KeyOne",
    b: "we don't care",
    c: "we don't care",
  },
  {
    a: "KeyTwo",
    b: "we don't care",
    c: "we don't care",
  },
  ],
  mySecondArray: [
  {
    KeyOne: "foo",
    KeyTwo: "bar"
  },
  {
    KeyOne: "hello",
    KeyTwo: "world"
  },
  ],

In this exemple, I want to display

  <table>
    <tr>
      <td>foo</td>
      <td>hello</td>
    </tr>
    <tr>
      <td>bar</td>
      <td>world</td>
    </tr>
  </table>

I tried :

<tr v-for="sa in mySecondArray">
  <td v-for="fa in myFirstArray">
    {{ sa + fa.a }}
  </td>
</tr>

in this case it displays [object Object].

I tried :

<tr v-for="sa in mySecondArray">
  <td v-for="fa in myFirstArray">
    {{ sa.concat('.',fa.a) }}
  </td>
</tr>

in this case console says: "sa.concat is not a function". I also tried with quotes, but it just concats the strings: "sa.KeyOne". How to make this final string used as a target and not just a string ?

2
  • This is not work? {{ sa }} {{ fa.a }} Commented Sep 1, 2021 at 16:32
  • {{ sa }} {{ fa.a }} displays all the "sa" object, followed by the good name of the column I want to target to, like that: {KeyOne: "foo",KeyTwo: "bar"}KeyOne Commented Sep 1, 2021 at 16:38

1 Answer 1

2

You can do something like this to get your result,

new Vue({
  el: '#app',
  data: {
    firstArray: [{
        a: "KeyOne",
        b: "we don't care",
        c: "we don't care",
    },
    {
        a: "KeyTwo",
        b: "we don't care",
        c: "we don't care",
    }],
    secondArray: [
    {
        KeyOne: "foo",
        KeyTwo: "bar"
    },
    {
        KeyOne: "hello",
        KeyTwo: "world"
    },
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">

<div id="app">
  <table class="table">
    <tr>
      <th>head1</th>
      <th>head2</th>
    </tr>
    <tr v-for="(sa1, index1) in secondArray" >
         <td v-for="(sa2, index2) in secondArray">
           {{secondArray[index2][firstArray[index1].a]}}
         </td>
    </tr>
  </table>
</div>

Hope this solves your problem!

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

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.