Merging two arrays upon the fulfillment of a promise in Vue.js

Within my code, I am storing data in the variable this.roomsData.room_photos

[ { "url": "https://api.example.com/uploads/609ee58907166.jpg" }, { "url": "https://api.example.com/uploads/609ee5898ba19.jpg" }, { "url": "https://api.example.com/uploads/609ee58994a10.jpg" }, { "url": "https://api.example.com/uploads/609ee589af635.jpg" }, { "url": "https://api.example.com/uploads/609ee589b0fc7.jpg" }, { "url": "https://api.example.com/uploads/609ee589cd79f.jpg" }, { "url": "https://api.example.com/uploads/609ee589d8d27.jpg" } ]

Additionally, I have another set of data stored in the variable this.roomsData.edit_room_photos, which is generated through the function:

uploadRoomImages: async function (file, progress, error, options) {
    try {
        console.log(file, options);
        const formData = new FormData()
        formData.append('room_photos', file)
        const result = await fetch('https://api.example.com/uploads_scripts/rooms.php', {
            method: 'POST',
            body: formData
        })
        progress(100) // (native fetch doesn’t support progress updates)
        return await result.json()
    } catch (err) {
        error('Unable to upload file')
    }

},

This component includes an input element as follows:

<FormulateInput
          type="image"
          name="room_photos"
          v-model="roomsData.edit_room_photos"
          label="Select Room Images To Upload"
          help="Select a png, jpg,webp or gif to upload."
          validation="required|mime:image/jpeg,image/png,image/gif,image/webp"
          :uploader="uploadRoomImages"
          error-behavior="live"
          multiple
/>

I am wondering how to merge the data stored in this.roomsData.room_photos with the data obtained from the function resolving in this.roomsData.edit_room_photos without removing any duplicates. I have attempted using object assign and array concat within the form submit handler, but encountered cyclic JSON errors.

If possible, I would like to combine both arrays without eliminating duplicate entries. How can this merging process be achieved?

Answer №1

If you want to utilize a computed value along with a setter function:

computed: {
  gallery_images: {
    get: function () {
      return [...this.galleryData.room_photos, ...this.galleryData.edit_room_photos];
    },
    set: function (newImages) {
      this.galleryData.edit_room_photos = newImages.slice(this.galleryData.room_photos.length);
    },
  },
},

Answer №2

If the outcome of calling uploadRoomImages() results in the value stored in roomsData.edit_room_photos, you can simply adjust the return value of uploadRoomImages() by using .concat to combine it with another array:

uploadRoomImages: async function (file, progress, error, options) {
    try {
        //...
        const result = await result.json()
        return result.concat(this.roomsData.room_photos)
    } catch (err) {
        error('Unable to upload file')
    }
},

Keep in mind that Array.prototype.concat() does not eliminate duplicates, so there is no need to worry about losing duplicate entries in this scenario.

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

What is the ideal JavaScript framework for implementing drag-and-drop, resize, and rotation features?

I am planning to create a web application that involves images and text with user handle functionalities such as drag-and-drop, resizing, and rotating. Although I have tried using JQuery UI js to implement drag-and-drop, rotate, and resize, I have encount ...

Trouble with highlighting the chosen menu item

I have been attempting to implement this code snippet from JSFiddle onto my website. Although I directly copied the HTML, used the CSS inline, and placed the Javascript in an external file, the functionality does not seem to be working properly. Feel free ...

Pattern matching to exclude specific characters

To enhance security measures, I am looking to restrict users from inputting the following characters: ~ " # % & * : < > ? / \ { | } . The key requirement is that all other characters should be permitted, while ensuring that only the sp ...

The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are ...

JavaScript modal component malfunctioning

I'm having an issue with the bootstrap 4 modal component. Whenever I click the button, the modal window fails to appear. Can someone offer assistance? <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> ...

Copy files using grunt, in accordance with the ant pattern, while excluding any variable directories

My task is to transfer files from the src/ folder to the dist/plugin directory. Since the version can potentially change, I would like to exclude the version number in all instances. Here is what I currently have: files[{ cwd: 'src' src ...

Struggling with implementing jquery Ajax and a php script to fetch information from a mysql database

I'm encountering issues with my current web app project in displaying a simple jpg image based on the selected radio button using jQuery AJAX along with a PHP script to interact with MySQL. Below is my ajax.js file: $('#selection').change( ...

Configuring multiple data sources in VueJS allows you to seamlessly connect

I have a Vue app with two data tables. Cash: [code, description, cash] Upload: [bank, id] In my update function, I need to retrieve [bank, id] from the Upload table and [cash] from the Cash table. Unfortunately, I am unsure how to do this. Can someone p ...

Developing an android application that handles a specific format of JSON data

I have received a JSON in the following format: var list=[{"Name":"arun","City":"xyx","CountryName":"KUWAIT"},"Name":"Amal","City":"abb","CountryName":"BAHRAIN"}]; This JSON is sent from my web server to my Android app as a String value. I need to conver ...

I need to modify the ng-style attribute multiple times within a JavaScript function

Here is the structure of my HTML: <nav id="card-set-menu-nav" ng-style="cardSetMenuNavStyle"> ... </nav> In my Javascript code using AngularJS, I have a function called openCardSetMenu: $scope.openCardSetMenu = function(cardSet) { $scope ...

There was a TypeError that occurred because the object did not have the 'ajax' method available

When attempting to initialize the quoteResults Javascript function on my Wordpress site, I encounter the following error in my console: Uncaught TypeError: Object #<Object> has no method 'ajax' I have successfully utilized the code below ...

In React (Next.js), the act of replacing a file is performed instead of adding a file

I kindly request a review of my code prior to making any changes. const test = () => { const [files, setFiles] = useState ([]); //I believe I need to modify the following statement. const handleFile = (e) => { const newFiles = [] for (let i= ...

Breaking down a javascript project

As the trend of splitting large JavaScript projects into separate files and then compiling them into a single distribution increases, I am eager to explore this workflow. While I have considered Node.js, npm, and Grunt for this purpose, I find the learning ...

Using React's useEffect function with an empty dependency array to trigger a change in the

In the React application I'm currently working on, the useEffect function is triggered whenever the prop value changes from an empty array to another empty array. I am fetching query parameters from the page and passing them down to a component that ...

Sending information from Ajax to PHP

Could anyone please explain the script provided above to me? I am attempting to pass the value of $user data so that I can utilize $_REQUEST['user'] within sort.php, but I am encountering difficulties. It seems to be passing in a long URL. $(fun ...

Remove a row from a table using the hyperlink reference

I am facing an issue where I want to delete a row in the table along with the corresponding database entry by clicking on a href link, but it doesn't work as expected: <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"& ...

Avoid creating a new Y class if there is already an existing X class

I'm a bit puzzled with my JavaScript (I'm still new to working with JS). Currently, I have the following: $('#left-nav-menu').hover(function () { $(this).toggleClass('menu-desktop_open_hover') }); I'd like to make it ...

ResponseXML in AJAXBindingUtil

I'm having an issue with the responseXML in my AJAX code. Here is an excerpt from my callback function: var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue; The problem I'm facing is that the linest ...

Issue with animated cursor function not activating when used with anchor links

I've spent hours searching for a solution but I can't seem to find one. I'm attempting to modify the codepen found at https://codepen.io/Nharox/pen/akgEQm to incorporate images and links, however, two issues are arising. The first issue is t ...

Retrieving the chosen value from Material-UI Autocomplete

Check out the sandbox code here: Problem Having an issue: The Autocomplete component is not retrieving values like the rest of my components. Clicking the Retrieve data button only retrieves values for creator, title, description, project, severity, and s ...