vue 将2个数组里面得值对应起来

https://img1.mukewang.com/5b684c4f0001eee605520467.jpg

如果两个数组的id相等我就要使第一个数组里面的activeName字段改为true,我是以这个来判断他是否加入收藏,为true就是加入为false就是没有加入。后台并没有返回给我这样一个状态的字段是我自己加的。所以需要收藏的列表数组要与我i当前的俩对比id如果id相等就说明莫一条记录是收藏状态就是改写为true. 这两个数组怎么判断major_id等于id的时候就使activeName字段为true:

    _this.listWish.forEach(function(a) {

      _this.major.forEach(function(item) {

        if (item.major_id == a.id) {

          _this.$set(a, 'activeName', true);

          _this.$set(a, 'wishId', item.wish_id);

        } else {

          _this.$set(a, 'activeName', false);

        }

      });

    });

    _this.listWish.forEach(function(a) {

      _this.major.forEach(function(item) {

        if (item.major_id == a.id) {

          _this.$set(a, 'activeName', true);

          _this.$set(a, 'wishId', item.wish_id);

        } else {

          _this.$set(a, 'activeName', false);

        }

      });

    });

    });

## 但是我这样循环后activeName这个字段的值没有被改写对,全部都是false。

心有法竹
浏览 2823回答 2
2回答

神不在的星期二

你这样循环不对啊,按照你的意思判断major_id等于id的时候就使activeName字段为true你这样循环如果倒数第二个数是匹配,设成true了,倒数第一个不匹配,那不就又是false了吗?你可以改成for循环for(let i = 0; i < _this.listWish.length; i ++){&nbsp; &nbsp; for(let j = 0; i < _this.major.length; j ++){&nbsp; &nbsp; &nbsp; &nbsp; if (item.major_id == a.id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.$set(a, 'activeName', true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.$set(a, 'wishId', item.wish_id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _this.$set(a, 'activeName', false);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

GCT1015

//你的应该这样写。保证只有一次修改,循环的时候只是为了判断有没有var _tag = false;_this.listWish.forEach(function(a) {&nbsp; _tag = false;&nbsp; _this.major.forEach(function(item) {&nbsp; &nbsp; if (item.major_id == a.id) {&nbsp; &nbsp; &nbsp; _tag &nbsp;= item.wish_id&nbsp; &nbsp; }&nbsp; });&nbsp; if(_tag){&nbsp; &nbsp; &nbsp; _this.$set(a, 'activeName', true);&nbsp; &nbsp; &nbsp; _this.$set(a, 'wishId', _tag);&nbsp; } else {&nbsp; &nbsp; &nbsp; _this.$set(a, 'activeName', false);&nbsp; }});//里面可以优化的地方就是如果内循环重复了,跳出来,这样可以少判断一点。//你的应该这样写。保证只有一次修改,循环的时候只是为了判断有没有var _tag = false;_this.listWish.forEach(function(a) {&nbsp; _tag = false;&nbsp; _this.major.forEach(function(item) {&nbsp; &nbsp; if (item.major_id == a.id) {&nbsp; &nbsp; &nbsp; _tag &nbsp;= item.wish_id&nbsp; &nbsp; }&nbsp; });&nbsp; if(_tag){&nbsp; &nbsp; &nbsp; _this.$set(a, 'activeName', true);&nbsp; &nbsp; &nbsp; _this.$set(a, 'wishId', _tag);&nbsp; } else {&nbsp; &nbsp; &nbsp; _this.$set(a, 'activeName', false);&nbsp; }});//里面可以优化的地方就是如果内循环重复了,跳出来,这样可以少判断一点。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Vue.js