将数组内的对象中的某一项值替换

项目场景:

最近遇到一个项目,它的接口获取到的图片资源不可用了但为了项目继续运行就想着用自己扒的网络图片地址替换。

  1. 接口获取到的数据格式:
{
    
    
  "status":0,
  "message":[
    {
    
    
    "id":1,
    "url":"http://www.itcast.cn/subject/phoneweb/index.html",
    "img":"http://m.itheima.com/images/slidead/mobile/20191213180241750x410.jpg"
    },        
    {
    
    
    "id":2,
    "url":"http://www.itcast.cn/subject/phoneweb/index.html",
    "img":"http://m.itheima.com/images/slidead/mobile/20191210154717750-410.jpg"
    },
    {
    
    
    "id":3,
    "url":"http://www.itcast.cn/subject/phoneweb/index.html",
    "img":"http://m.itheima.com/images/slidead/mobile/20190327135101750x410-%E4%BC%A0%E6%99%BA%E9%BB%91%E9%A9%AC%E7%A7%BB%E5%8A%A8%E7%AB%AF%E5%B9%BB%E7%81%AF.jpg"
     }
  ]
}
  1. 自己为替换图片资源准备的数据格式:
			imgUrlList:[
				{
    
    id:1,img_url:"https://img.pconline.com.cn/images/product/5784/578421/q.jpg"},
				{
    
    id:2,img_url:"https://img.pconline.com.cn/images/product/6012/601274/45.jpg"},
				{
    
    id:3,img_url:"https://img.pconline.com.cn/images/product/1086/1086487/0.jpg"},
				{
    
    id:4,img_url:"https://img.pconline.com.cn/images/product/6156/615692/846a19fea2cabb0e.jpg"},
				{
    
    id:5,img_url:"https://img.pconline.com.cn/images/product/5784/578421/q.jpg"},
				{
    
    id:6,img_url:"https://img.pconline.com.cn/images/product/1200/1200911/Z6-2-Z.jpg"},
				{
    
    id:7,img_url:"https://img.pconline.com.cn/images/product/5550/555050/g510-01.jpg"},
				{
    
    id:8,img_url:"https://img.pconline.com.cn/images/product/1381/1381391/sf.jpg"},
				{
    
    id:9,img_url:"https://img.pconline.com.cn/images/product/7101/710192/1-5.jpg"},
				{
    
    id:10,img_url:"https://img.pconline.com.cn/images/product/4358/435856/Deskjet1000.jpg"}
			]

问题描述

逐个替换从接口获取到的img_url的值


解决方案:

			// 获取推荐商品
			async getHotGoodsList(){
    
    
				const res = await this.$myRequest({
    
    
					url:"/api/getgoods?pageindex=1"
				})
				// 如果status == 0 代表接口有数据返回
				if(res.data.status == 0){
    
    
					// 替换imgurl地址,index为了逐个替换对应下标的img_url值
					res.data.message.forEach((item,index)=>{
    
    
						console.log(this.imgUrlList[index].img_url)
						// 给this.imgUrlList下标
						item.img_url = this.imgUrlList[index].img_url
					})
					// 将整理好的数据保存到hotGoodsList
					this.hotGoodsList = res.data.message
				}
			}

猜你喜欢

转载自blog.csdn.net/weixin_46278178/article/details/128212818