【响应数据的处理】如何将响应的商品列表数据按照对应的类别,放到数组中

接口(可访问)(POST):https://api.it120.cc/zcr/shop...
接口文档:https://api.it120.cc/doc.html...

请求了商品列表的接口

getGoodsList() {
    this.axios
        .post('/shop/goods/list/v2', {
            categoryId: ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975'],
        })
        .then(res => {
            this.goodsList.push(res.result)
        })
    },

接口返回的数据是一个数组
image.png

需求:把响应的数据以每个类别放到数组中,方便渲染

我使用了以下方法:

// 获取 商品列表
    getGoodsList() {
      const CATEGORY_ID = ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975']
      for (var i = 0; i < CATEGORY_ID.length; i++) {
        this.axios
          .post('/shop/goods/list/v2', {
            categoryId: CATEGORY_ID[i],
            pageSize: 6,
          })
          .then(res => {
            this.goodsList.push(res.result)
          })
      }
    },
<div class="category">
  <div class="category-item" v-for="(item, index) in category" :key="item.id">
    {{item.name}}
    <div class="children">
      <div class="children-item" v-for="item1 in goodsList[index]" :key="item1.id">
        <a href="#">
          <img :src="item1.pic" alt="">
          <div class="name">{{item1.name}}</div>
          <div class="price">{{item1.minPrice}}元</div>
        </a>
      </div>
    </div>
  </div>
</div>

E64142CA-62D4-49AF-9A9C-9B7E33804D8F.png
但响应的数据并没有按照我请求参数的顺序来进行排序,导致商品列表与分类不相同
Filmage 2022-02-11_103013.gif

【问:如何将响应的商品列表数据按照对应的类别,放到数组中。我是小白,如果可以请说下具体的代码和描述】

阅读 2.6k
4 个回答
getGoodsList() {
    const categoryId = ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975']
    this.axios
        .post('/shop/goods/list/v2', {
            categoryId: categoryId,
        })
        .then(res => {
            //this.goodsList.push(res.result)
            this.goodsList = categoryId.map(item=>{
                return (res.result||[]).filter(resItem=>resItem.categoryId === item).slice(0,6);
            });
        })
    },
this.$set(this.goodsList, i, res.result)

看图猜代码,建议弄清楚goodsList是全部类别的集合还是个别类别的集合,问题就不是问题了~🤣

// 获取 商品列表
getGoodsList() {
    const CATEGORY_ID = ['263919', '263920', '263921', '263923', '269499', '263924', '263925', '263926', '263927', '263975'];
    CATEGORY_ID.forEach((categoryId, index) => {
        this.axios.post('/shop/goods/list/v2', {
            categoryId: categoryId,
            pageSize: 6,
        }).then(res => {
            this.goodsList.splice(index, 1, res.result);
        });
    });
},
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题