javascript - Include new parameter in object literal and retrieve

I have a base object that I define using an object literal:

var obj = {
   key1   : 'value1',
   key2   : 'value2'
}

Now, I want to pass this object to a function and extend it like this:

myFunction( obj + { key3 : 'value3' } );

// The parameter will be:
{
   key1   : 'value1',
   key2   : 'value2',
   key3   : 'value3'
}

or

myFunction( obj + { key2 : 'new value2' } );

// The parameter will be:
{
   key1   : 'value1',
   key2   : 'new value2'
}

The use of the + operator in this context is not correct. Is there a way to achieve this?

EDIT: Do you want to permanently alter obj? - No, I would like to be able to reuse it as a base for the next call.

Answer №1

Utilizing the object spread syntax available in ES2018 or TypeScript 2.1 allows you to easily manage properties in objects.

// Properties on the right update properties on the left
// Overwrite properties from obj
myFunction( { ...obj, key3: 'value3' } );
// Don't overwrite properties from obj
myFunction( { key3: 'value3', ...obj } );

For those using ES2015, the Object.assign method serves a similar purpose.

// Object.assign(a, b, c, ..) - copy properties from b to a, then from c to a etc.
// Overwrite properties from obj
myFunction( Object.assign({}, obj, { key3: 'value3' }) );
// Don't overwrite properties from obj
myFunction( Object.assign({ key3: 'value3' }, obj) );

Check out a demonstration here.

var obj = { key1: 'value1', key2: 'value2'}
console.log('-- Object Spread --');
console.log({ ...obj, key3: 'value3' });
console.log('overwrite');
console.log({ ...obj, key2: 'NEW2' });
console.log('no overwrite');
console.log({ key2: 'NEW2', ...obj });

console.log('-- Object Assign --');
console.log(Object.assign({ key3: 'value3' }, obj));
console.log('overwrite');
console.log(Object.assign({}, obj, { key2: 'NEW2' }));
console.log('no overwrite');
console.log(Object.assign({ key2: 'NEW2' }, obj));

console.log('-- Original Object unchanged --');
console.log(obj);

Answer №2

To modify obj, simply adjust it before passing it:

var obj = { /* data */ };

obj.key3 = 'value3';
myFunction(obj);

Do you wish to permanently change obj? - No, I would like to reuse it for the next call as a base.

If that's the case, you will need to create a copy of obj and modify the copy — either before calling myFunction:

var obj = { /* data */ };
var extension = {key3: 'value3'};

myFunction($.extend({}, obj, extension));

or provide both obj and the "extension" to myFunction:

var obj = { /* data */ };
var extension = {key3: 'value3'};

myFunction(obj, extension);

and let myFunction handle the task:

function myFunction(base, ext)
{
    if (typeof base === 'object' && typeof ext === 'object')
    {
        base = $.extend({}, base, ext);
    }

    // add remaining function logic here
}

If you are already using jQuery or don't mind using it, $.extend() can be very helpful for this purpose.

Answer №3

If you want to enhance objects without modifying the original one, you can create a function to do so. Here's an example:

var originalObject = {name: 'foo'};

function extendNonDestructive(source, newProperties) {
  function Temp() {} 
  Temp.prototype = source;
  var newObj = new Temp;
  for (var prop in newProperties) {
    if (newProperties.hasOwnProperty(prop)) {
      newObj[prop] = newProperties[prop]
    }
  }
  return newObj
}

var enhancedObject = extendNonDestructive(originalObject, {lastName: 'bar'}); // Does not alter originalObject

Keep in mind that there is also Object.create, which provides more flexibility compared to the method used in my code snippet, but it requires ES5 or newer.

Answer №4

To easily add properties to an existing object and return the new object in one line, you can leverage both the Object.fromEntries and Object.entries functions:

console.log(
   Object.fromEntries(
    Object.entries({
      t:4,
      f:2
    })
    .concat(
      Object.entries({
            q:2,
            p:9
      })
    )
  )
);

 
This method also works well if you only need to modify a single property of an existing object. Simply add the object with the updated property to replace it, for example:

....concat(Object.entries({t:2}))...

This approach will specifically change the value of the t property within the original object.

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 method for obtaining the CSS text content from an external stylesheet?

I've spent countless hours trying to achieve the desired results, but unfortunately, I haven't been successful. Below is a summary of my efforts so far. Any helpful tips or suggestions would be greatly appreciated. Thank you in advance. Upon rec ...

What is the reason behind router.base not functioning properly for static sources while running 'npm run build' in Nuxt.js?

Customizing Nuxt Configuration const BASE_PATH = `/${process.env.CATEGORY.toLowerCase()}/`; export default { router : { base : BASE_PATH }, } In addition, there is a static source for an image in the component: <img src="/mockups/macbookpro_01. ...

In Three JS, shader x, y, z coordinates are based on the orientation of the object rather than the scene itself

Animating the x,y,z coordinates of vertices in a sphere-like manner with horizontal rings around the center using attributes on a THREE.Points() object has been quite intriguing. Initially, with a MeshStandardMaterial(), tilting the Points object along the ...

How to update the selected autocomplete item in Vue using programming techniques?

Although I am still learning Vue, consider the following scenario: <v-autocomplete v-model="defaultUser" :hint="`User: ${defaultUser.username}`" :items="users" :item-text="item =>`${item.firstName} - $ ...

Unlocking the Power of Marionette.CompositeView: Passing Parameters to Marionette.ItemView

Is there a way to access the app.vent from Marionette.ItemView? One solution might be to pass a parameter (app.vent) to Marionette.ItemView from Marionette.CompositeView. Here's the code snippet: // view/compositeView.js define([ 'marionet ...

Tips for utilizing the useContext hook in Next.js

I'm facing an issue with persisting information between different pages using nextjs and the useContext hook. Despite changing a variable in one page, it reverts back to its default value when navigating to another page. Below is a glimpse of the dir ...

Having trouble retrieving data sent via ajax in PHP

Currently, I am using Ajax to send a variable in my PHP file. Here's the code snippet: getVoteCount: function(){ App.contracts.Election.deployed().then(function(instance) { for(i=0; i<4; i++){ instance.candidates(i).then(functi ...

Comparing the distinction between assigning values to res and res.locals in a Node.js application using Express

Greetings! I am inquiring about the utilization of res (Express response object) and res.locals in Express. During my exploration of nodejs, I came across a code snippet that consists of a middleware (messages.js), a server (app.js), and a template (messa ...

What could be the reason behind the ineffectiveness of my recently acquired Google Maps API key

For years, I had a function working with the Google API flawlessly. However, after obtaining a new API key, everything seems to have gone haywire. The issue is that there is no output after the `alert(address)` line because the code from `geocoder.geocod ...

Encourage (or kindly request) the user to refresh the browser

I manage a website that heavily relies on javascript and ajax functionality. I have found ways to make users refresh their browsers upon initial loading, but what about after they have already been using the site? I am looking to improve the speed of the ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...

Issues with JSON data not functioning properly when using file system in JavaScript

When attempting to parse a JSON file, I encountered some errors. The file is located in a directory within my JavaScript file, under the 'fs' in a folder named "recipes." Within this folder, there are 3 JSON files, each representing a separate ob ...

Node.js: Extract the object's name and value that are sent from the frontend

I'm in the process of creating a microservice using nodejs. The request is returning the following JSON. { "distCd": "abcd", "distName": "parentLife Distributor (TOD)", "stateCd": "", "subdistInd": false, "maindistInd": true ...

Making Angular2 Templates More Efficient with Array.prototype.filter()

I have a variable named networkInterface that includes an array called services. My objective is to create a checkbox input that indicates whether a specific service_id exists within the services array of the networkInterface. An illustration of JSON `int ...

What is the best way to connect a JavaScript file to an HTML file in an Express app?

I have my NodeJS server set up with Express, utilizing Handlebars as the rendering engine. app.use(express.static(publicDirPath)) (...) app.engine("hbs",hbs({ extname: "hbs", defaultView: "main", layoutsDir: path.join(srcDirP ...

Erroneous deletion issue in React list causing removal of incorrect item

While working on creating a todo list in React, I faced an issue when trying to implement a delete function. The problem arose when attempting to delete an item - instead of removing the selected item, React ended up deleting everything except that specif ...

If the item has an active class, apply a new class to the parent element and all of its

If I have code like the example below and want to add the show class to the parent and ancestors. // The last `nav-item` has the `active` class <div class="nested-group nested-item show"> <div class="nested-item show"> <div class="n ...

I am sometimes experiencing issues with activating ajax code using Bootstrap 3 modal

I'm stumped trying to find a solution for this issue. Currently, I am utilizing the bootstrap modal to retrieve ajax content from a specified URL. To prevent content overlap, I am using $.removeData() when reloading the content. The problem arises w ...

Select a user at random from the reactions in the message

Is there a way to select a user at random from message reactions on Discord? Despite going through all the documentation, I'm still unsure about how to do this. ...

Determining the file extension type of an uploaded file using JavaScript

In my new file upload system, users have the option to upload both images and videos. After uploading a file, I provide a preview of the uploaded content. Desired Outcome: My goal is to display only ONE preview based on the type of file (image or video). ...