JS 轻松搞定数据处理,让前端开发更高效

前言

常规情况下,我们可以把后台返回给我们的数据直接渲染在前台页面上,但不排除一些特殊的情况需要我们对源数据进行处理,例如 element 上传组件,在编辑页面中的回显指定参数为 nameurl,但是后台返回的如果不是这两个字段名,就需要我们对源数据做进一步的处理。


未处理之前的数据

在这里插入图片描述


需求:

将后台返回 originalList 数组中每一个对象中的 imgs 数组中的每一个对象中的 imgUrluserName 字段改为 urlname,话不多说,下面直接看代码实例。


完整代码

<template>
  <div></div>
</template>
<script>
export default {
  data() {
    return {
      // 模拟接口返回数据
      originalList: [
        {
          isShow: 1,
          correct: true,
          imgs: [
            {
              id: "0",
              url: "https://imge1c2fcf985084fe0ad01c7",
              name: "测试数据111",
            },
            {
              id: "1",
              url: "http:://54",
              name: "测试数据222",
            },
          ],
        },
        {
          isShow: 1,
          correct: false,
          imgs: [
            {
              id: "3",
              url: "https://imge1c2ftegwfqge1c7",
              name: "测试数据333",
            },
            {
              id: "4",
              url: "https://imge1785faewfa01c7",
              name: "测试数据444",
            },
            {
              id: "5",
              url: "https://imgfwqfgdhtad01c7",
              name: "测试数据555",
            },
            {
              id: "6",
              url: "https://imge1cfegdsdfvse0ad01c7",
              name: "测试数据666",
            },
          ],
        },
        {
          isShow: 1,
          correct: false,
          imgs: [
            {
              id: "7",
              url: "https://imge68erwt4ye0ad01c7",
              name: "测试数据777",
            },
          ],
        },
        {
          isShow: 1,
          correct: true,
          imgs: [
            {
              id: "8",
              url: "https://imge1c5fagd0ad01c7",
              name: "测试数据888",
            },
          ],
        },
        {
          isShow: 0,
          correct: true,
          imgs: [
            {
              id: "9",
              url: "https://imge1c2fc86wfegrhad01c7",
              name: "测试数据999",
            },
          ],
        },
      ],
    };
  },
  mounted() {
    // 判断是为了防止空数组报错
    if (this.originalList) {
      this.originalList.forEach((item) => {
        // 调用方法处理数据
        item["imgs"] = this.formatting(item.imgs);
      });
    }
    // 打印处理好的数据
    console.log(this.originalList, "处理好的数据");
  },
  methods: {
    // 处理接口返回数据的方法
    formatting(data) {
      let newImgs = [];
      data.map((item) => {
        newImgs.push({
          imgUrl: item.url,
          codeId: item.id,
          userName: item.name,
        });
      });
      return newImgs;
    },
  },
};
</script>

处理后的数据

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水星记_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值