Utilizing the object spread feature in JavaScript on an object that contains properties with potentially undefined data objects

Hey there, I'm currently in the process of populating an empty placeholder object which serves as a v-model for vue, although this particular detail is not crucial to the issue at hand. The object that I am extending the original one with might contain undefined objects within it. However, it is important for me to maintain the structure of the initial object regardless of what the incoming one looks like.

For instance, let's consider Object 1:

let object1 = { a : '', b : '', c : {name : 'Mark', title: 'Mr'}}

And then we have Object 2, which could sometimes appear like this:

let object2 = { a : 'AAA', b : 'BBB', c : undefined}

My goal is to preserve the structure of object 1 even if object 2 has the property c set as undefined. So, in this scenario:

let object1 = { a : 'AAA', b : 'BBB', c : {name : 'Mark', title: 'Mr'}}

Thank you for your assistance!

Answer №1

One way to approach this is by incorporating object2 as the first element and then introducing the property c as the second:

  object1={...object2,c:object1.c}

Alternatively,

   object1={...object2,  c : object2.c ? object2.c : object1.c}

Answer №2

To utilize spread syntax effectively, consider creating a helper proxy function that selectively filters out keys with values equal to undefined

let object1 = {a: '', b: '', c: {name: 'Mark', title: 'Mr'}}

let object2 = {a: 'AAA', b: 'BBB', c: undefined}

const result = { ...defined(object1), ...defined(object2) }

console.log(result)

function defined(obj) {
  return new Proxy(obj, {
    ownKeys() {
      return Object.keys(obj).filter(key => obj[key] !== undefined)
    }
  })
}

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

Ensure that the focus() function is called only after the completion of the jQuery append

I'm using both append() and focus() functions to set focus on the first input element in the appended DOM. However, Internet Explorer is slow in appending the elements which causes the focus not to work as intended. Is there an alternative method to s ...

Show Angular if it is in the array

Presently, I have an ng-repeat function to display comments on articles. It is structured like this: <div ng-repeat="comment in comments"> <li class="item" ng-class-even="'even'"> <div class="row"> ...

Generate a personalized design with just a snippet of an image

I am interested in creating a unique layout using a small image fragment. For instance, I have a 30*30 px piece of an image and I want to generate a new image of size 200*200 px resembling a photo frame. I have explored various gd library options in PH ...

Converting a unix timestamp to a Date in TypeScript - a comprehensive guide

To retrieve the unix timestamp of a Date in plain JavaScript and TypeScript, we can use this code snippet: let currentDate = new Date(); const unixTime = currentDate.valueOf(); Converting the unix timestamp back to a Date object in JavaScript is straight ...

List of dates in React Native for Today and Tomorrow

In React Native, I am looking to create a dynamic list that displays the next seven days starting from today (assuming today is Monday): Today - Tomorrow - Wednesday - Thursday - Friday - Saturday - Sunday - Monday <- My goal is to show a total of seve ...

methods for converting and saving base64 image strings

I am using PHP to pull content from a table that includes a base64 image string. I would like to remove or drop the base64 string. Just so you know, the text and base64 image are coming from the Summernote WYSIWYG editor. I hope someone can assist me wit ...

Encountering an error when using Angular Material virtual scroll in conjunction with Angular-UI

Trying to incorporate Angular material's virtual scroll feature on angular-ui-tree is proving to be a bit challenging. The error message that keeps popping up is: Controller 'uiTree', which is required by directive 'uiTreeNode', ...

Create a custom overlay for an image that is centered horizontally and does not have a fixed width

I'm working with this HTML setup: <div class="container"> <img class="image" /> <div class="overlay"> <div class="insides">more content here</div> </div> &l ...

Choosing between creating a class with a shared instance or not

I'm curious if my class is shared across instances: for example, I have a route that looks like this: /student/:id When this route triggers the controller (simplified version): module.exports = RecalculateStudents; const recalculateActiveStudent ...

Vuetify - Implementing a Sidebar Menu with Expandable Submenus

I am currently working on creating a Navigation Drawer with nested list items, similar to the structure in the Vuetify Material Dashboard. Below is an overview of my code: <v-navigation-drawer v-model="drawer" app clipped> <v-list de ...

What is the most effective way to append a new key-value pair to the end of an OrderedMap?

Possible duplicate: Adding Items in OrderedMap using Immutable.js Utilizing redux store and Immutable js with OrderedMap. Structure of Redux store: { "app": { "name": "Test app", "dataPack":{ "chemID": "aaaa", ...

Struggling to dynamically update the URL within a "a href" tag, JavaScript is failing to reflect the changes in the output

Currently, I am attempting to use JavaScript to replace the URLs in the HTML. However, I seem to be encountering an issue where the new URLs do not apply when clicking on the images, even though testing with "alert" shows that the values are correct. Any a ...

Delete an item without a guardian

This situation differs from the one discussed in Remove dom element without knowing its parent?, because their element has a parentNode. While I am familiar with removing an element through its parentNode, creating a new element poses a different challeng ...

Tips for setting up a select dropdown in AngularJS using ng-options when the value is an object

How can I set the initial selection of a select field using ng-options? Consider the items we have: $scope.items = [{ id: 1, label: 'aLabel', subItem: { name: 'aSubItem' } }, { id: 2, label: 'bLabel', subItem: { ...

The parent navigation bar in HTML and CSS is hogging more space compared to its children

In the midst of my vuejs project, I have encountered an issue relating to the size of elements. Specifically, my header consists of a logo and a navbar. The navbar seems to be extending the size of the header unnecessarily. Upon inspection, I noticed tha ...

Prevent hovering on the date picker header

I have a bootstrap date picker inside a table with the hover option. When accessing the date picker, the first two rows displaying the month and day are being overridden by CSS from the table, and after hovering, the side text turns white. Here is a worki ...

Received an error stating "Uncaught TypeError: Unable to access the property 'PropTypes' of undefined" while encountering problems with React Bootstrap. Additionally, facing issues with ReactDOM not being defined due to

Currently, I am in the process of developing a React-JS website with Express handling the backend. For authentication, I am utilizing react-router and react-stormpath. I have also incorporated webpack into the project. However, I have encountered some ch ...

What is the best way to structure a web server along with a socket.io server?

I am curious about the capabilities of node.js Is it feasible to utilize multiple server.js files? For example, could there be a primary "server.js" that directs users to another directory where a separate server.js manages websocket connections using so ...

jQuery DatePicker Not Displaying Calendar

I've been attempting to implement a date picker in jQuery. I've included the necessary code within the head tag: <link rel="stylesheet" type="text/css" media="screen" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jqu ...

Using Jquery to Insert Numbers Inside Brackets to Selection

I am struggling to calculate the sum of numbers in jQuery for selection fields. Currently, my code looks like this. $(function() { $("select").change(function() { updateTotal(); }); updateTotal(); }); function updateTotal() { ...