Reputation: 121
I'm trying to convert an array into a specially formatted string. I can't get it done because I'm rendering the object dynamically and looping through it:
<ul class = "details" v-for = "(value, propertyName) in items[this.index]" :key = "value.id">
<li>{{value}}</li>
</ul>
For example, let's say the rendered values are:
['Bob', 'Charlie', 'Annie']
'Richard'
I want to modify the array, and render it as:
'Bob' 'Charlie' 'Annie'
'Richard'
I have already tried {{values.join(" ")}}
.
Upvotes: 2
Views: 524
Reputation: 138356
You could conditionally use Array.prototype.join()
on the value
based on whether it's an Array
. Then {{value.join(' ')}}
should work as you expect:
<li v-if="Array.isArray(value)">{{value.join(' ')}}</li>
<li v-else>{{value}}</li>
new Vue({
el: '#app',
data: () => ({
items: [
{id: 1, names: ['Bob', 'Charlie', 'Annie']},
{id: 2, names: 'Richard'},
],
index: 0,
}),
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<label>Index = 0
<input type="radio" name="index" v-model="index" value="0">
</label>
<label>Index = 1
<input type="radio" name="index" v-model="index" value="1">
</label>
<ul class = "details" v-for = "(value, propertyName) in items[this.index]" :key = "value.id">
<li v-if="Array.isArray(value)">{{value.join(' ')}}</li>
<li v-else>{{value}}</li>
</ul>
</div>
Upvotes: 1
Reputation: 4723
Array can be converted to a String by using any of the following methods:
1- .toString()
['a', 'b', 'c'].toString();
// 'a,b,c'
2- Coerce to string
['a', 'b', 'c'] + [];
// 'a,b,c'
['a', 'b', 'c'] + '';
// 'a,b,c'
3- .join()
['a', 'b', 'c'].join();
// 'a,b,c' (defaults to ',' separator)
['a', 'b', 'c'].join('');
// 'abc'
['a', 'b', 'c'].join('-');
// 'a-b-c'
4- JSON.stringify()
JSON.stringify(['a', [1], 'b', 'c']);
// '['a', [1], 'b','c']'
5- Manually, if can't use built-in method...
function arrayToString(arr) {
let str = '';
arr.forEach(function(i, index) {
str += i;
if (index != (arr.length - 1)) {
str += ',';
};
});
return str;
}
Upvotes: 1