Reputation: 183
Im have a small problem with proccessing arrays I have data that I receive by API request
I need to check if category.parent_id = category.id If this expression is executed Then take the title of that row and put instead of parent_id And the display the category.title
Im try different ways to solved this problem but i dont have any results This is my code
<tr v-for="(category, $index) in categories">
<td>{{$index + 1}}</td>
<td>{{category.title}}</td>
<td v-for="item in category['id']" v-if="item === category.parent_id">true</td>
<td>{{category.created_at | moment("DD, MMMM, YYYY")}}</td>
<td></td>
</tr>
2: {id: 8, title: "test2", alias: "test2-5e80113c71e4f", parent_id: null, keywords: "test2",…}
id: 8 title: "test2" alias: "test2-5e80113c71e4f" parent_id: null keywords: "test2" description: null created_at: "2020-03-29T04:00:00.000000Z" updated_at: "2020-03-29T04:00:00.000000Z" 3: {id: 10, title: "test4", alias: "test4-5e80116ab3b6c", parent_id: 7, keywords: "test4",…} id: 10 title: "test4" alias: "test4-5e80116ab3b6c" parent_id: 7 keywords: "test4" description: null created_at: "2020-03-29T04:00:00.000000Z" updated_at: "2020-03-29T04:00:00.000000Z" 4: {id: 11, title: "test5", alias: "test5-5e80168707b53", parent_id: null, keywords: "test5",…} id: 11 title: "test5" alias: "test5-5e80168707b53" parent_id: null keywords: "test5" description: null created_at: "2020-03-29T04:00:00.000000Z" updated_at: "2020-03-29T04:00:00.000000Z"
Upvotes: 0
Views: 721
Reputation: 304
You can't really use v-if and v-for on the same element. Best to put the v-if on a parent element. After that, try to put this:
<tr v-for="(category, index) in categories" :key="index">
<td>{{index + 1}}</td>
<td>{{category.title}}</td>
<td v-if="category.parent_id">{{ getParent(category.parent_id) }}</td>
<td>{{ new Date(category.created_at).toLocaleString('ru-RU')}}</td>
<td></td>
</tr>
And method:
getParent(childrenParentId) {
// Check if exist parent or was deleted
return this.categories.find(cat => childrenParentId === cat.id)
? this.categories.find(cat => childrenParentId === cat.id).title
: "Parent was deleted and not exist";
}
Maybe its better to add a method with that code and call when render.
Find search first occurrence in your array of dicts and return that object.
Its important that if not exist parent will crash (you cant search ['title'] of undefined) so you will have to delete in cascade parent to childrens or remove in childrens that parent.
Codesandbox with test working: https://codesandbox.io/s/jolly-bas-6uhkx
Upvotes: 1