Reputation: 427
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:
avatar
property
andaxios.patch()
code to upload the avatar file?Upvotes: 1
Views: 1371
Reputation: 11
userinfo.profile.avatar
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);
});
Upvotes: 1
Reputation: 368
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"
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
Upvotes: 1