Transfer a loaded object to a different object using Javascript

Starting with the title, I have an initialized object that looks like this

"travellerDetails": { 
       "traveller_1": { 
              "Full Name": "", 
              "Gender": "", 
    }, "traveller_2": { 
             "Full Name": "", 
             "Gender": "",
    }, "traveller_3": { 
              "Full Name": "", 
              "Gender": ""
    } 
}

Now, when I retrieve my data object through an Ajax request

"travellerDetails": { 
           "traveller_1": { 
                  "Full Name": "John Doe", 
                  "Gender": "M", 
        }, "traveller_2": { 
                 "Full Name": "Jane Doe", 
                 "Gender": "F",
        }
    }, 

An issue arises when attempting to save the retrieved data into the initialized object.

bookingForm.travellerDetails = data.travellerDetails;

I expected traveller_3 to remain as "" since I only have 2 travelers in the loaded data. However, it causes an error unless the initialized object matches the same size as the one loaded via Ajax. How can I copy the loaded object into the initialized one despite their different sizes?

Thank you!

Answer №1

To leverage the Object Spread Operator in ES6, you can utilize it in your code.

Give this a shot:

bookingInfo.travelerDetails = { ...bookingInfo.travelerDetails, ...data.travelerDetails}
;

This operation essentially entails creating a new object that combines the original properties of bookingInfo.travelerDetails with any matching properties from data.travelerDetails. It also includes any additional properties from data.travelerDetails, while maintaining values for properties unique to bookingInfo.

Please bear in mind that this syntax is specific to ES6; if you're using babel, ensure you have the necessary plugin installed.

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 mistakes did I make in my Ajax code?

My aim is to dynamically add items to my listbox when a button is clicked, and then retrieve the value of the added item in the listbox using ajax. Below is the code I have tried: $('#right').click(function () { alert("Start process"); ...

The v-autocomplete component's watcher is not functioning as intended

Despite numerous attempts, I have been unable to get my watcher to work properly with the v-autocomplete component. <template> <v-app id="inspire"> <v-content> <v-form ref="form" v-model="valid" :lazy-validation="lazy"> ...

Ways to retrieve the mapState property within a method

Is there a way to access the count property within the method while working with vuex? Take a look at my code provided below: Screenshot of Code: https://i.stack.imgur.com/xNUHM.png Error Message [Vue warn]: Computed property "count" was assigned to bu ...

Node: How can I retrieve the value of a JSON key that contains a filename with a dot in

I have a JSON file named myjson.json, with the following structure: { "main.css": "main-4zgjrhtr.css", "main.js": "main-76gfhdgsj.js" "normalkey" : "somevalue" } The purpose is to link revision builds to their original filenames. Now I need to acce ...

Wait until the npm.load callback is returned before returning module.exports

I am currently facing a situation similar to the one depicted in this simplified example. main.js var settings = require('../settings.js'); console.log(settings.globalData); //undefined The settings.js file relies on an external module (npm) t ...

Ensuring Vue.js methods are correctly configured to handle Axios asynchronous requests

My Vue.js application fetches complex data from an API using Axios and then visualizes the data. Here is a snippet of my code: { data: () => ({ data: null, loading: false, errored: false, loadingMessage: '' }), methods: ...

Navigating through the React components using react-router and accessing the props can

Is there a way to access this.props from the <Router>'s onUpdate function? I need to know the current route and access this.props.route in order to identify the page (name). Unfortunately, I haven't found any resources on how to achieve thi ...

Troubleshooting a JQuery accordion malfunction within a table

I am populating the data dynamically. However, the Accordion feature is not functioning correctly. JSFiddle link http://jsfiddle.net/aff4vL5g/360/ Please note: I am unable to modify the HTML structure. Current table Desired output The first accordio ...

Modify the color of a set of div elements when clicked

Is there a way to change the background color of all divs with a common attribute value (#id for example) after clicking on one of the divs that shares the same attribute value? This is what I have tried so far: $('.group').click(function(){ ...

Get the value of a specific option within a React-bootstrap Form component

A special Form has been created to retrieve the selected value from an option. import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; import { useState } from "react"; export default function Cu ...

Toggle the visibility of a div element and smoothly scroll to it on the page

Upon clicking the form, my goal is to show or hide it and scroll down to view the form. The current code I have in place seems to work after the first click. However, on the initial click, it shows the form but fails to scroll down. Any insights on what I ...

Issue with v-mask not being applied after data fetch in VUE.js

I recently started learning VUE.js and ran into a common beginner issue. After fetching some JSON data from a REST service and populating a v-model with the returned data, I noticed that the mask was not being applied correctly. However, when I manually ...

The function to set the state in React is malfunctioning

I'm currently in the process of developing a website where I utilize fetch to retrieve information and display it to the user. Initially, I opted to save this data in a state variable, but for some reason, it's not functioning as expected. Upon ...

Running multiple languages locally may encounter issues, however, Codepen operates smoothly without any problems

While conducting research, I came across several options for creating multilingual websites. After implementing one method (jQuery), I noticed some slowness in translation and processing the information. Additionally, it only partially worked in the normal ...

No departure animation employed - Polymer

I am working on a project that involves animating a paper-icon-button with spin and opacity effects when hovering over an image using the on-mouseenter and on-mouseleave events. Everything works smoothly when hovering over the image, but I am facing an is ...

Exploring the depths of Mongoose queries with recursive parent references

I'm attempting to replicate the functionality of this MongoDB example using Mongoose, but it seems more complicated in Mongoose. Am I trying to force a square peg into a round hole? This source is taken from http://www.codeproject.com/Articles/521713 ...

arrange according to a specific sequence

I have been working on developing a JavaScript card game. I am looking for a way to match four consecutive numbers in a list. Currently, I have a loop structure that seems complex: cards = [{card:'h7'},{card:'c8'},{card:'h ...

When it comes to identifying a click outside of an element, the Jquery or Javascript function may encounter some challenges specifically with Internet Explorer

After reviewing various solutions online, I noticed that they all function properly on Chrome and Firefox but encounter issues with Internet Explorer when interacting with an SVG. For instance, consider the following code snippet: $(document).on("click",( ...

Has getCurrentInstance() in Vue 3 been phased out?

In my research, I've come across mentions of the getCurrentInstance() function in older documents and code, but it doesn't seem to be included in the current Vue 3 documentation. Is the getCurrentInstance() function deprecated? If it is, what i ...

Unable to integrate JWT authentication into `hapi.js`

Looking to implement the JWT strategy into my Hapi.js backend for heightened security and improved authentication processes. Here's a snippet of my server code: const Hapi = require('@hapi/hapi'); const Joi = require('joi'); const ...