0

I have the following json-object returned via response

enter image description here

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

asked Jul 30, 2017 at 15:05

4 Answers 4

2

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])
answered Jul 30, 2017 at 15:10
Sign up to request clarification or add additional context in comments.

Comments

2

Try response['movies[]']. Also, you could console log the response object and inspect what is inside it

answered Jul 30, 2017 at 15:08

1 Comment

I get undefined in both cases
2

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[]"]);

answered Jul 30, 2017 at 15:10

Comments

1

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);
 })
 }
});
answered Jul 30, 2017 at 15:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.