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

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])
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

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

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);
    })
  }
});

Comments

Your Answer

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.