简体   繁体   中英

How can i add "ids" to data fetched from an outside api?

Good evening everyone,

I have the following code for fetching the data from an api i prepared:

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(BOOKS_API);
      setBookData(result.data);
    };
    fetchData();
  }, []);

This is how the data looks (raw api call) ->

{
    "bookName": "Thus Spoke Zarathustra",
    "bookGenre": "Philosophical",
    "pageCount": 327,
    "bookAuthorName": "Friedrich Nietzsche",
    "isbnNumber": "9780521602617"
  },
  {
    "bookName": "Beyond good and evil",
    "bookGenre": "Philosophical",
    "pageCount": 301,
    "bookAuthorName": "Friedrich Nietzsche",
    "isbnNumber": "9780394703374"
  },

My website functionalities require an additional "id" property, a 'final' object would look like this:

{
    id: 1,
    bookName: 'Thus Spoke Zarathustra',
    bookGenre: 'Philosophical',
    pageCount: 327,
    bookAuthorName: 'Friedrich Nietzsche',
    isbnNumber: '9780521602617',
  },

My question is - How can i append this data fetched from my api with an "id" field, which will always be enumerated from 1 - n? (n-number of rows fetched)

Thank you in advance

Just call .map on the response and set the id field to the index+1:

 let bookData = []; const setBookData = (data) => { bookData = data; } const apiResponse = [ { "bookName": "Thus Spoke Zarathustra", "bookGenre": "Philosophical", "pageCount": 327, "bookAuthorName": "Friedrich Nietzsche", "isbnNumber": "9780521602617" }, { "bookName": "Beyond good and evil", "bookGenre": "Philosophical", "pageCount": 301, "bookAuthorName": "Friedrich Nietzsche", "isbnNumber": "9780394703374" } ]; setBookData(apiResponse.map((el, index) => { return { ...el, "id": index+1 } })); console.log(bookData);

useEffect(() => {
    const fetchData = async () => {
        const { data } = await axios(BOOKS_API);
        const formattedResult = data.map((res, index) => {
            return { ...res, id: index + 1 }
        });
      
        setBookData(formattedResult);
    };

    fetchData();
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM