首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何合并2个对象Vue.Js

如何合并2个对象Vue.Js
EN

Stack Overflow用户
提问于 2020-03-29 10:25:14
回答 1查看 117关注 0票数 0

我有一个处理数组的小问题,我有通过API请求接收到的数据

如果执行此表达式,则需要检查category.parent_id = category.id,然后获取该行的标题,并放置parent_id,并显示category.title

我尝试了不同的方法来解决这个问题,但我没有任何结果这是我的代码

代码语言:javascript
复制
                                    <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标题:"test2“别名:"test2-5e80113c71e4f”parent_id:空关键词:"test2“描述:空created_at:"2020-03-29T04:00:00.000000Z”updated_at:"2020-03-29T04:00:00.000000Z“3:{id: 10,标题:"test4",别名:"test4-5e80116ab3b6c",parent_id: 7,关键词:"test4",…} id: 10标题:"test4“别名:"test4-5e80116ab3b6c”parent_id: 7关键词:"test4“描述:空created_at:"2020-03-29T04:00:00.000000Z”updated_at:"2020-03-29T04:00:00.000000Z“4:{id: 11,标题:"test5",别名:"test5-5e80168707b53",parent_id: null,关键词:"test5",…} id: 11标题:"test5“别名:"test5-5e80168707b53”parent_id: null关键词:"test5“描述: null created_at:"2020-03-29T04:00:00.000000Z”updated_at:"2020-03-29T04:00:00.000000Z“

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-29 10:46:42

你不能在同一个元素上使用v-if和v-for。最好将v-if放在父元素上。在那之后,试着放这个:

代码语言:javascript
复制
<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>

和方法:

代码语言:javascript
复制
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";
}

也许用这些代码添加一个方法并在渲染时调用会更好。

在您的字典数组中查找搜索的第一个匹配项并返回该对象。

重要的是,如果不存在父元素,它将崩溃(你不能搜索未定义的'title‘),所以你将不得不级联父元素到子元素中删除,或者在子元素中删除该父元素。

具有测试工作的Codesandbox:https://codesandbox.io/s/jolly-bas-6uhkx

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60909465

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档