I have the following json-object returned via response
the function
function getUserList() {
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "paul rudd",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response); // prints the object
}
});
}
My question is how the movies-array are accessed in javascript? I cannot access it via response - if I do i get "undefined" returned.
i.e response.movies
undefined
or response.movies[0]
uncaught typerror cannot read property [0] of undefined
4 Answers 4
The property of the object appears to be "movies[]", not "movies", for which you can use bracket notation to get the value of
console.log(response["movies[]"][0])
Comments
Try response['movies[]']. Also, you could console log the response object and inspect what is inside it
1 Comment
in your back end you're returning with bad naming , so
to access that array you've to access it as below response.["movies[]"]
see below sample :
response = { "movies[]": ["1","2","3"] };
console.log(response["movies[]"]);
Comments
movies is array, use $.each or .forEach()
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "paul rudd",
movies: ["I Love You Man", "Role Models"]
},
success: function(response) {
$.each(response.movies, function(index, value){
// prints the object
console.log(value);
})
}
});