Home » vue » Vue.js – Binding array with multiple keys with same name

Vue.js – Binding array with multiple keys with same name

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am trying to pass multiple values through Vue.js, under the same key name to keep it dynamic.

This is my code:

Input.vue:

<search-popover :fields="[{
 names: ['Title1', 'value1'],
 names: ['Title2', 'value2'],
}]"></search-popover>

Now, in my Popover.vue file, I only get the last element of the :fields:

<ul v-for="field in fields">
    <li>
       <h5>{{ field.names[0] }}</h5>
       {{ values[field.names[1]]}}
    </li>
</ul>

Will output:

Title2
Value2

How can I do, so I can set the values of :fields dynamically, so I can access the array in my v-for, and it will output:

Title1
Value1

Title2
Value2
Answers:

the problem is in

:fields="[{
 names: ['Title1', 'value1'],
 names: ['Title2', 'value2'],
}]"

where you are creating 1 array containing only 1 object.

(when an object has duplicated properties, the latter one is used. Therefore, { names: ['Title1', 'value1'], names: ['Title2', 'value2'], } is equilavant to { names: ['Title2', 'value2'], })

What you want is probably 1 array containing 2 objects, which should be

:fields="[ 
    { names: ['Title1', 'value1'] }, 
    { names: ['Title2', 'value2'] }, 
]"

###

You are not able to have the same key name more than once or the last key will be the only one display.

Correctly iterating through names must be with its own object. Like this:

:fields = "[
  { names: ['Title1', 'value1'] }, 
  { names: ['Title2', 'value2'] }
]"

As written by @jacobgoh