> 文章列表 > JS 处理后台返回的数据

JS 处理后台返回的数据

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>

处理后的数据

在这里插入图片描述

名医视频