简体   繁体   中英

use axios.patch with a nested JSON

There's a nested JSON object defined in the server side code of the website that I'm working on, like this:

userinfo:{
   first_name,
   last_name,
   profile:{
      avatar,    //here is the field I need to access!!!
      id,
      some other properties...
   }
}

and I want to upload the avatar picture and as you can see, the avatar property is inside a JS object that is itself inside another JS object,

I'd appreciate it if someone help me with these questions:

  1. how can I access the avatar property and
  2. how should I write the axios.patch() code to upload the avatar file?
  1. To access nested keys inside a Javascript Object, you can use the dot (.) notation. In your case, you can doo something like this
// assuming an object with value
const obj = {
  userinfo: {
    first_name: 'first name',
    last_name: 'last name',
    profile:{
      avatar: 'https://some-url',    //field to be accessed
      id: 'xxx-xxx-xxx',
      some other properties...
    }
  }
}

// logging avatar
console.log(obj.userinfo.profile.avatar); // prints "https://some-url"
  1. Axios Patch is an async function, you can use it like this -
axios.patch('https://url-endpoint.co', { 
  avatar: obj.userinfo.profile.avatar
}).then(res => {
  // do something on success
  console.log(res);
}).catch(err => {
  // do something on error
  console.log(err);
});

You can read more about axios here - https://github.com/axios/axios#request-method-aliases

  • Answer for number 1, You can get avatar property in:

userinfo.profile.avatar

  • Answer for number 2, to upload the avatar file use axios you can try this code:

var formData = new FormData();

formData.append('file', userinfo.profile.avatar);

await axios.post('your endpoint url', formData, {
  headers: {
    'Content-Type': 'application/json'
  }   
})
.then(response => {
  // handle response
  console.log(response);
.catch(error => {
  // handle error
  console.log(error.response);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM