Transform the API response array into a different format, ready to be passed as a prop to a

Looking to incorporate the Vue Flipbook component into my project, which requires an array of image URLs for the "pages" prop. I am fetching post responses from the WordPress REST API.

My goal is to extract the "image" property from the response array and convert it into a new array of image URLs. Typically, I would iterate through the posts using v-for=post in posts in my template and display the image using post.image_full within the loop.

Here is how the Flipbook component is set up:

<Flipbook
   class="flipbook"
   :pages="imagesArray" <--- insert images array here
   v-slot="flipbook"
   ref="flipbook"
>
</Flipbook>

Below is the structure of My Posts.vue component:

export default {
  name: 'GridOne',
  props: {
    page: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      request: {
        type: 'posts',
        params: { 
          per_page: this.$store.state.site.posts_per_page,
          page: this.page
        }, 
        showLoading: true 
      },
      totalPages: 0
    }
  },
  computed: {
    posts() {
      return this.$store.getters.requestedItems(this.request) <--- response array extraction
    }
  },
  methods: {
    getPosts() {
      return this.$store.dispatch('getItems', this.request)
    },
    setTotalPages() {
      this.totalPages = this.$store.getters.totalPages(this.request)
    }
  },
  created() {
    this.getPosts().then(() => this.setTotalPages())
  }
}

Answer №1

To modify an array in JavaScript, you can utilize the "map" function which creates a new array based on the original one.

// For example, if we have an array called "response"
const response = [{name: 'picture 1', url: 'https://uri.com/img1'}, ...]

// We can use the map function to transform it like this
response.map(item => {
    return {
       ...item,
       full_image: item.url
    }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular ng-show does not seem to evaluate properly

After receiving the JSON array object below: "Tools": [ { "name": "Submit a Claim", "position": 1, "isOn": true, "alert": null }, { "name": "My Recurring Claims", "position": 2, "isOn": true, "alert": null }, { "name": "Online Enrollment ...

I encountered an issue with Expo commands where it was throwing an error: "Module not found: 'minizlib'"

Every time I attempt to execute commands like expo init, expo start, or simply expo, it returns the following error message: Error: Cannot find module 'minizlib' Require stack: - /usr/local/lib/node_modules/expo-cli/node_modules/tar/lib/pack.js ...

I am no longer able to connect to mySQL using node js

I recently upgraded my node version, and now I'm facing issues accessing my database through my application. I have tried various solutions such as: - Changing the route to 127.0.0.1. - Adding my port number 3306. - Including socketPath: '/Applic ...

Troubles with submitting jQuery validation plugin via AJAX

Whenever I try to use the jQuery validation plugin for validating a form within a Bootstrap modal, the validation does not work and the form cannot be submitted. This is the code for the Bootstrap modal form: <div class="modal fade" id="form-content" ...

What is the best way to replace testcaferc.json browsers using the command line interface (CLI

Scenario: I am facing a situation where I aim to execute Testcafe in docker within a remote environment that necessitates running Testcafe through its command-line interface. I intend to utilize the .testcaferc file that I use for local testing to avoid m ...

How to disable items in Vuetify's v-select without having to modify the object

After searching extensively, I have only come across information in the official documentation indicating that v-select's items can be disabled by setting the object's disable property to true as shown below: {text: 'text1', disabled: t ...

What is the most effective method for accessing, editing, and outputting large JSON files in Node JS?

Task at hand: I need to handle large amounts of data (1 GB & more) in JSON format, perform formatting, parse the data, restructure the JSON, and return the newly formatted JSON as a response. What is the best approach for this situation? I read on a blog ...

Activate the feature of smooth shading using Three.js

When rendering an object with textures using MTL and OBJ files in Three.js, I encountered an issue where my model was displayed with flat shading. How can I enable smooth shading? var scene = new THREE.Scene(); var mtlLoader = new THREE.MTLLoader(); mtl ...

Struggling to save the resolved data from a promise in Node.js to a variable

I am currently utilizing nodejs to develop REST APIs and I am facing an issue with storing resolved data from multiple promises into a single variable. Here is a snippet of the code I am working with: var resultset={}; function getAllTeams() { retu ...

Concentrate on Selecting Multiple Cells in ag-Grid (Similar to Excel's Click and Drag Feature)

Is there a way to click and drag the mouse to adjust the size of the focus box around specific cells in ag-Grid? This feature is very handy in Excel and I was wondering if it is available in ag-Grid or if there is a workaround. Any insights would be apprec ...

What is the reason behind the TypeError thrown when attempting to assign to `NaN` or `undefined` in JavaScript

A.S.: The question pertains to the type of error rather than the phenomenon itself "use strict" results in a TypeError when system variables like NaN and undefined are modified. But why is it categorized as a TypeError instead of a SyntaxError? Edit: I ...

Implementing AngularJS to store data in a JSON object

Imagine having an animals.json file with the following details: { "animals": { "elephant": { "size": "large" }, "mouse": { "size": "small" } } } Now, let's say this data is being added to the controller scope: anim ...

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...

Feed JSON data into a jQuery function using JavaScript

A rudimentary Google Apps Script Web App has been created with the sole purpose of displaying JSON data in an HTML drop-down list. The JSON file is stored in Google Drive. Code inspiration taken from: http://jsfiddle.net/manoj_admlab/Mta5b/3/ However, we ...

Dealing with a jQuery/Javascript/AJAX response: sending a string instead of an integer as a parameter to a

Trying to figure out how to handle passing integers as strings in JavaScript within an AJAX response. Here is the code snippet: message+="<td class='yellow' onclick='open_flag("+i+j+")'>"; The message variable is eventually inse ...

What is the best way to center an infowindow in Google Maps API V3 when working with a map canvas that has a narrow width?

As an illustration of my point, I have put together a sample page: The issue I am facing is with a narrow map canvas and an infowindow in it. Upon clicking the marker, the map sometimes fails to center properly and the marker along with the infowindow sli ...

Issue with CornerstoneJs React restoreImageIdToolState causing annotations to fail to load automatically post-execution

Once this code is executed, I need the annotations to appear without having to hover over the cornerstoneViewport. const restore = () => { let element; const stack = { currentImageIdIndex: 0, imageIds, }; console.log(dico ...

Error: Surprising token found in ReactJS application on CodeSandbox

Encountering an unexpected token on line 5 error in my ReactJS project when testing it on CodeSandbox. Interestingly, the app runs smoothly without errors on my local machine. import React, { Component } from 'react'; import Header from ' ...

What is the best method for transferring updated data from the frontend to the backend without needing to store any unchanged values?

After importing a list from a database using axios and storing it in a variable called tasks, each object may resemble the following structure: tasks: [ { title: 'some text here' }, { completed: false }, ] If there are 2000 or 3000 of ...

Handling ajax errors when connection to the internet is disrupted

When working with ajax calls, I have encountered an issue with the "error" handler not functioning correctly when the internet connection is lost. Is there an alternative handler that can be used for these scenarios? $.ajax({ type: "GET", ur ...