簡體   English   中英

如何循環使用 flat() 創建的 arrays 數組?

[英]How can I loop over an array of arrays created with flat()?

我使用 flat() 將 3 個 JSON 文件組合成一個數組,然后通過數組循環到 output 它在控制台中的內容。 它輸出從下面的 3 個 JSON 文件創建的 arrays 數組。

這是控制台 output:

{books: Array(3)}books: (3) [{…}, {…}, {…}]__proto__: Object
{movies: Array(3)}movies: (3) [{…}, {…}, {…}]__proto__: Object
{posts: Array(3)}posts: (3) [{…}, {…}, {…}]__proto__: Object

我無法遍歷每個內部 arrays 以訪問它們的屬性/值。 任何人都可以提供一些幫助嗎? 謝謝!

這是我的代碼...

JAVASCRIPT:

let finalResult;

const urls = ['books', 'movies', 'posts'];

Promise.all(
urls.map(url =>
    fetch('json/' + url + '.json')
        .then(e => e.json())
    )
).then(data => {
    finalResult = data.flat();

    finalResult.forEach(array => {
      console.log(array); // returns the array of arrays I want to loop through to get the property-values
    });
});

書籍.json

{
  "books": [
    {
      "title": "Eloquent JavaScript, Second Edition",
      "description": "JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications."
    },
    {
      "title": "Learning JavaScript Design Patterns",
      "description": "With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."
    },
    {
      "title": "Speaking JavaScript",
      "description": "Like it or not, JavaScript is everywhere these days-from browser to server to mobile-and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position."
    }
  ]
}

電影.json

{
  "movies": [
    {
      "title": "History of the World Part I",
      "description": "A 1981 American sketch comedy film written, produced, and directed by Mel Brooks. Brooks also stars in the film, playing five roles: Moses, Comicus the stand-up philosopher, Tomás de Torquemada, King Louis XVI, and Jacques, le garçon de pisse."
    },
    {
      "title": "Jaws",
      "description": "a 1975 American thriller film directed by Steven Spielberg, based on Peter Benchley's 1974 novel of the same name. In the film, a man-eating great white shark attacks beachgoers at a summer resort town, prompting police chief Martin Brody (Roy Scheider) to hunt it with the help of a marine biologist (Richard Dreyfuss) and a professional shark hunter (Robert Shaw). "
    },
    {
      "title": "The Exorcist",
      "description": "When a 12-year-old girl is possessed by a mysterious entity, her mother seeks the help of two priests to save her."
    }
  ]
}

帖子.json

{
  "posts": [
    {
      "title": "Done",
      "description": "I can't take it anymore."
    },
    {
      "title": "Finished",
      "description": "The story of a young man who has finished his sandwich."
    },
    {
      "title": "Concluded",
      "description": "An epic take of a meeting that has conluded."
    }
  ]
}

我不確定這是否正是您想要的,因為您沒有指定確切的 output,但我認為您明白如何做到這一點。

Object.entries / Object.keys / Object.values是您正在尋找的東西:

 const books = {"books":[{"title":"Eloquent JavaScript, Second Edition","description":"JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications."},{"title":"Learning JavaScript Design Patterns","description":"With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."},{"title":"Speaking JavaScript","description":"Like it or not, JavaScript is everywhere these days-from browser to server to mobile-and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position."}]} const movies = {"movies":[{"title":"History of the World Part I","description":"A 1981 American sketch comedy film written, produced, and directed by Mel Brooks. Brooks also stars in the film, playing five roles: Moses, Comicus the stand-up philosopher, Tomás de Torquemada, King Louis XVI, and Jacques, le garçon de pisse."},{"title":"Jaws","description":"a 1975 American thriller film directed by Steven Spielberg, based on Peter Benchley's 1974 novel of the same name. In the film, a man-eating great white shark attacks beachgoers at a summer resort town, prompting police chief Martin Brody (Roy Scheider) to hunt it with the help of a marine biologist (Richard Dreyfuss) and a professional shark hunter (Robert Shaw). "},{"title":"The Exorcist","description":"When a 12-year-old girl is possessed by a mysterious entity, her mother seeks the help of two priests to save her."}]} const posts = {"posts":[{"title":"Done","description":"I can't take it anymore."},{"title":"Finished","description":"The story of a young man who has finished his sandwich."},{"title":"Concluded","description":"An epic take of a meeting that has conluded."}]} const yourThen = (data) => { const finalResult = data.map(e => Object.entries(e)).flat() finalResult.forEach(([k, v]) => console.log(k, v)) return finalResult } yourThen([books, posts, movies])
 .as-console-wrapper { max-height: 100%;important: top; 0; }

使用Object.entries和解構。

 const finalResult = [{"books":[{"title":"Eloquent JavaScript, Second Edition","description":"JavaScript lies at the heart of almost every modern web application, from social apps to the newest browser-based games. Though simple for beginners to pick up and play with, JavaScript is a flexible, complex language that you can use to build full-scale applications."},{"title":"Learning JavaScript Design Patterns","description":"With Learning JavaScript Design Patterns, you'll learn how to write beautiful, structured, and maintainable JavaScript by applying classical and modern design patterns to the language. If you want to keep your code efficient, more manageable, and up-to-date with the latest best practices, this book is for you."},{"title":"Speaking JavaScript","description":"Like it or not, JavaScript is everywhere these days-from browser to server to mobile-and now you, too, need to learn the language or dive deeper than you have. This concise book guides you into and through JavaScript, written by a veteran programmer who once found himself in the same position."}]}, {"movies":[{"title":"History of the World Part I","description":"A 1981 American sketch comedy film written, produced, and directed by Mel Brooks. Brooks also stars in the film, playing five roles: Moses, Comicus the stand-up philosopher, Tomás de Torquemada, King Louis XVI, and Jacques, le garçon de pisse."},{"title":"Jaws","description":"a 1975 American thriller film directed by Steven Spielberg, based on Peter Benchley's 1974 novel of the same name. In the film, a man-eating great white shark attacks beachgoers at a summer resort town, prompting police chief Martin Brody (Roy Scheider) to hunt it with the help of a marine biologist (Richard Dreyfuss) and a professional shark hunter (Robert Shaw). "},{"title":"The Exorcist","description":"When a 12-year-old girl is possessed by a mysterious entity, her mother seeks the help of two priests to save her."}]}, {"posts":[{"title":"Done","description":"I can't take it anymore."},{"title":"Finished","description":"The story of a young man who has finished his sandwich."},{"title":"Concluded","description":"An epic take of a meeting that has conluded."}]}] finalResult.forEach(obj => { // destructure first entry key, value pair. const [[type, array]] = Object.entries(obj); console.log('-----------> Type: ', type); array.forEach(item => console.log(item)); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM