小能豆

How I get data from JSON file?

javascript

In Javascript, I have a file resulting from using Axios.get command from a loop, but I can’t get the data inside it. This is the command:

for (let i=0; i<names.length; i++){
    promises.push(
    axios.get(urlpend, {params: {USER_ID1: names[i]}}).then(res => {
    Authors.push(res);
    })
    )
    Promise.all(promises).then(()=> console.log("promises: ",names));

I can see the file at console.log(Authors), this is it:

Authors:
[]
0:
  config: {transitional: {...}, adapter:Array(2), transformRequest: Array(1),timeout: 0,
  data: Array(2)
    0: {Author_name:"Mark", Author_lastName: "Twain", title:"Tom Sawyer"}
    1: {Author_name:"Mark", Author_lastName: "Twain", title:"Huckleberry Finn"}
    [[Prototype]]: Array(0)
  headers: AxiosHeaders {access-control-headers: "*", access-control-allow-methods: "*",
  request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials
  status: 200
  statusText: "OK"
  [[Prototype]]: Object
1:
  config: {transitional: {...}, adapter:Array(2), transformRequest: Array(1),timeout: 0,
  data: Array(2)
    0: {Author_name:"Edgar Allan", Author_lastName: "Poe", title:"The Black Cat"}
    [[Prototype]]: Array(0)
  headers: AxiosHeaders {access-control-headers: "*", access-control-allow-methods: "*",
  request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials
  status: 200
  statusText: "OK"
  [[Prototype]]: Object

I tried to get the variables inside “data” but couldn’t. I can’t understand how the array is composed. Almost every attempt to capture the data results “undefined”

Authors[data] –> “data” is not defined no-undef or Authors[0] –> undefined

I tried to get something like this:

books = [{Author_name:”Mark”, Author_lastName: “Twain”, title:”Tom Sawyer”}, {Author_name:”Mark”, Author_lastName: “Twain”, title:”Huckleberry Finn”}, {Author_name:”Edgar Allan”, Author_lastName: “Poe”, title:”The Black Cat”}]


阅读 65

收藏
2023-12-21

共1个答案

小能豆

It looks like the Authors array contains Axios response objects, and each response object has a data property which is an array of books. To access the books, you need to go one level deeper.

Here’s how you can access the books array:

// Assuming Authors is an array of Axios response objects

let books = [];

Authors.forEach(response => {
  // Check if the response has a 'data' property
  if (response.data && Array.isArray(response.data)) {
    // Concatenate the books array with the books from the current response
    books = books.concat(response.data);
  }
});

console.log(books);

This code iterates through each response object in the Authors array, checks if it has a data property, and if so, concatenates the books from that response to the books array.

Now, the books array should contain all the books from the Axios responses. You can further process or display this array as needed.

2023-12-21