反应未定义的对象值,而存在对象值

时间:2020-04-16 15:58:40

标签: javascript reactjs ecmascript-6 javascript-objects

我有问题,我有一个这样的对象列表:

(0)
id: 1
service_name: "ETHYLENE OXIDE STERILIZATION"
service_description: "ETHYLENE OXIDE STERILIZATION Ethylene oxide (EO) is the leading technology. "

(1)

id: 2
service_name: "ETHYLENE STERILIZATION"
service_description: "ETHYLENE OXIDE is good material. "

上面是对象列表,表示两个对象的列表,现在我想在每个对象中添加一个新的键,即图像键,我已经完成了:

 for (let i=0;i<mydata.length;i++){

        axios.get(api_url)
        .then(res=>{

          for (let it=0;it<res.data.length;it++){
            mylist[it]=res.data[0].service_image
          }

          Object.assign(mydata[i],{"images":mylist}) // making a new key in each object

          mylist=[]

        })

添加新密钥后打印时:

id: 1
service_name: "ETHYLENE OXIDE STERILIZATION"
service_description: "ETHYLENE OXIDE STERILIZATION Ethylene oxide (EO) is the leading technology. "
images:['url1','url2']

(1)

id: 2
service_name: "ETHYLENE STERILIZATION"
service_description: "ETHYLENE OXIDE is good material"
images:['url3','url4']

我已经成功地将新的关键图像添加到对象mydata的列表中,但是当我通过console.log(mydata.images)访问images属性时,当我打印console.log(mydata)时,它给了我未定义的状态,但是它存在整个列表,我也可以看到图像属性。

我不是问题所在,有人可以建议我

1 个答案:

答案 0 :(得分:2)

mydata是一个数组,您的图像位于:

mydata[0].images
mydata[1].images