Отображение вложенного JSON несмотря на имя переменной ключа и символ двоеточия - PullRequest
0 голосов
/ 09 апреля 2019

Я пытаюсь добраться до вложенных слоев, таких как «заголовок», в данных JSON.Тем не менее, первое свойство является переменным, и символ : внутри не помогает либо

"ISBN:nnnnnnnnnnnn"

Отображение значений на компонент, подлежащий деструктуризации, используя:

renderBooks()
    {
        return this.state.books.map((book, index) =>
            <BookDetail key={index} book={book} />);
    }

    render()
    {
        console.log(this.state);
        return (
            <ScrollView style={{ flex: 1 }}>
                {this.renderBooks()}
            </ScrollView>
        );
    }

Компонент:

const BookDetail = ({ book }) =>
{
    const { title, author,... } = book;

return (
        <Card>
            <CardSection>
                <View style={styles.headerContentStyle}>
                    <Text style={headerTextStyle}>{title}</Text>
                    <Text>{author}</Text>
                </View>
            </CardSection>
        </Card>
    );
};

JSON:

[
    {
        "ISBN:9780192853462": {
            "publishers": [
                {
                    "name": "Oxford University Press, USA"
                }
            ],
            "identifiers": {
                "isbn_13": [
                    "9780192853462"
                ],
                "openlibrary": [
                    "OL7384519M"
                ],
                "isbn_10": [
                    "0192853465"
                ],
                "librarything": [
                    "49548"
                ],
                "goodreads": [
                    "334271"
                ]
            },
            "subtitle": "A Very Short Introduction (Very Short Introductions)",
            "title": "Social and Cultural Anthropology",
            "url": "https://openlibrary.org/books/OL7384519M/Social_and_Cultural_Anthropology",
            "number_of_pages": 168,
            "cover": {
                "small": "https://covers.openlibrary.org/b/id/119856-S.jpg",
                "large": "https://covers.openlibrary.org/b/id/119856-L.jpg",
                "medium": "https://covers.openlibrary.org/b/id/119856-M.jpg"
            },
            "subjects": [
                {
                    "url": "https://openlibrary.org/subjects/ethnology",
                    "name": "Ethnology"
                }
            ],
            "publish_date": "April 7, 2000",
            "key": "/books/OL7384519M",
            "authors": [
                {
                    "url": "https://openlibrary.org/authors/OL656666A/John_Monaghan",
                    "name": "John Monaghan"
                },
                {
                    "url": "https://openlibrary.org/authors/OL2662612A/Peter_Just",
                    "name": "Peter Just"
                }
            ],
            "ebooks": [
                {
                    "formats": {},
                    "preview_url": "https://archive.org/details/socialculturalan00mona",
                    "availability": "restricted"
                }
            ]
        }
    }

1 Ответ

0 голосов
/ 10 апреля 2019

Вы можете сделать свою собственную копию объекта book, вся информация о книге обернута в атрибут ISBN, лично я бы сделал это простым полем внутри объекта книги.

let data = {
  "ISBN:9780192853462": {
      "publishers": [
          {
              "name": "Oxford University Press, USA"
          }
      ],
      "identifiers": {
          "isbn_13": [
              "9780192853462"
          ],
          "openlibrary": [
              "OL7384519M"
          ],
          "isbn_10": [
              "0192853465"
          ],
          "librarything": [
              "49548"
          ],
          "goodreads": [
              "334271"
          ]
      },
      "subtitle": "A Very Short Introduction (Very Short Introductions)",
      "title": "Social and Cultural Anthropology",
      "url": "https://openlibrary.org/books/OL7384519M/Social_and_Cultural_Anthropology",
      "number_of_pages": 168,
      "cover": {
          "small": "https://covers.openlibrary.org/b/id/119856-S.jpg",
          "large": "https://covers.openlibrary.org/b/id/119856-L.jpg",
          "medium": "https://covers.openlibrary.org/b/id/119856-M.jpg"
      },
      "subjects": [
            {
                "url": "https://openlibrary.org/subjects/ethnology",
                "name": "Ethnology"
            }
        ],
        "publish_date": "April 7, 2000",
        "key": "/books/OL7384519M",
        "authors": [
            {
                "url": "https://openlibrary.org/authors/OL656666A/John_Monaghan",
                "name": "John Monaghan"
            },
            {
                "url": "https://openlibrary.org/authors/OL2662612A/Peter_Just",
                "name": "Peter Just"
            }
        ],
        "ebooks": [
            {
                "formats": {},
                "preview_url": "https://archive.org/details/socialculturalan00mona",
                "availability": "restricted"
            }
        ]
    }
};


//let isbn = Object.keys(obj).find(item => item.match(/ISBN:\d/));

const destructureBook = (obj) => {
  let book = {};
  Object.keys(obj).map(function(key) {
    if(key.match(/ISBN:\d/)) book['isbn'] = key;
    Object.keys(obj[key]).map(field => book[field] = obj[key][field]);
  });
  return book;
}
// destructure the return of the function
const {isbn, title, publish_date } = destructureBook(data);
console.log(isbn, title, publish_date)
...