How can you append a value to an array within a freshly duplicated object using JavaScript ES6?

When working with ES6, there is a convenient new method for copying objects which helps in handling immutable states:

let oldObj = { foo: 1}; // { foo: 1 }

let newObj = { ...oldObj, bar: 2 }; // { foo: 1, bar: 2}

But what if I want to accomplish the following:

let oldObj = { foo: [1] }; // { foo: [1] }

let newObj = ??? // { foo: [1, 2] }

Does anyone know how this can be achieved?

Answer №1

const updatedObj = { ...originalObj, bar: [1, 2, 3] }

If you're interested, check out the benefits of using Immer -

Answer №2

I prefer the answer provided by Zerkms as it offers a more general approach, especially when dealing with objects that have multiple keys in addition to the array:

{ ...oldObj, foo: [...oldObj.foo, 2] }

Thanks to @Zerkms for sharing this solution.

Answer №3

One way to manipulate values dynamically is by using the spread operator and a variable.

let oldObj = { foo: [1] }; // { foo: [1] }
let newObj = { ...oldObj, foo: [1, 2] } // { foo: [1, 2] }
console.log(newObj)

let oldObj2 = { foo: [1] }; // { foo: [1] }
let bar = 2
let newObj2 = { foo:  [...oldObj.foo, bar] } // { foo: [1, 2] }
console.log(newObj2)

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

Error: Attempting to access a property of an undefined object resulting in TypeError (reading 'passport')

I am currently working on a project that requires me to display user profiles from a database using expressjs and mongoDB. However, I have encountered an issue and would appreciate any solutions offered here. Here is the code from my server: const express ...

How to include THREE.js in a Node module along with custom variables and functions

I have been working on adapting a THREE.js project that originally included JavaScript files directly in HTML into a node module-based setup. My goal is to utilize webpack to bundle the project into a single file (bundle.js) so that the HTML only needs to ...

Issue with IntersectionObserver not detecting intersection when the root element is specified

I am encountering an issue with my IntersectionObserver that is observing an img. It works perfectly when the root is set to null (viewport). However, as soon as I change the root element to another img, the observer fails to detect the intersection betwee ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Ways to identify if a JavaScript file has already been packed

Hello everyone! I'm currently working on a Windows application using C# that minifies CSS files and packs JS files in bulk. I've come across a challenge where if the user selects a JS file that has already been packed, it will actually increase t ...

If variable is greater than, hide the division element

I have a variable called lineNum that increases each time I click on an h1 element I'm attempting to use an 'if' statement to hide a div by setting its display to none, but for some reason, I can't seem to get the 'if' code r ...

What causes the vertical scroll bar to shift on its own?

I'm puzzled by the behavior of the vertical scroll bar when clicking on "Line 9" - it automatically moves to the top position and subsequent clicks don't affect it. Can someone shed light on why this happens and how to resolve it? I am using Fire ...

My navbar list elements are not functioning properly due to an issue with JS. Does anyone have a solution to resolve this issue

As I work on creating a website using a free template, I encountered an issue with JS that I am not very familiar with. After conducting some research, it seems like the problem lies within the JS code. Below are the relevant snippets of HTML and JS code: ...

What sets apart angular.merge from angular.extend?

Could someone kindly shed some light on the distinction between angular.merge and angular.extend? Additionally, can you explain what a deep copy is and in what situations it should be utilized? ...

Revamped React Navigation Version 4

Currently, I am in the process of developing a web application using React and incorporating React Router v4 for navigation purposes. My main goal is to redirect to a new page upon successful completion of the signup process (when the user signs up). Do yo ...

Mastering AJAX with Django

I'm currently struggling to understand how to create an AJAX function, as all the tutorials I've come across seem too complicated for me. This is my HTML code: <a href="{% url pay_provider id=statement.statement_id %}" id="pay_provider">P ...

What are the steps to turn off response data compression in an Express server?

How can I receive the 'Content-Length' response from the server without gzip compression enabled? I am using a compression middleware for this purpose: const shouldCompress = (req, res) => { if(req.headers['x-no-comprassion']) { ...

Building an Empty AngularJS Response with the Combination of Spring Boot and MongoDB

In my AngularJS application, I collect user input and store it in painting objects. These objects are then sent to my Spring Boot backend which saves them to a MongoDB server and returns an ID. However, when attempting to POST data to the server, I receive ...

Converting a json array into a map with the help of Underscore.js

My challenge involves parsing a JSON array into a map object, with the key being the state and the value being an array of objects that share the same state. An example JSON data set is provided below: { "totalRec": 10, "content": [ { "name" ...

In my attempt to simulate redis using jest and javascript, I've noticed that whenever I try to access redis.mock.instance[0], it consistently returns as empty

I'm currently attempting to simulate redis with jest and JavaScript, but I'm encountering an issue where accessing redis.mock.instance[0] always returns empty. RedisWrapper.js: const Redis = require('ioredis'); const REDIS_USER_TTL = 6 ...

Tips for utilizing addEventListener to navigate to a different HTML page when a button is clicked

Is there a way to utilize addEventListner for redirecting to the next page? I want to create a function where clicking a button will redirect to another HTML page. How can I achieve this with code? This is what my HTML looks like: <button>submit< ...

Guide to configuring the API key within the Stampery API.JS script

Currently, I'm in the process of configuring Stampery but I'm facing difficulty locating where to insert the string API key within the API.JS file. The documentation mentions setting the STAMPERY_TOKEN as the API key, but I'm unsure how to p ...

I am unable to access Angular $scope in the HTML Template, although I can view it in the console log

I have been following some online tutorials and using the angularjs-template to start learning Angular. However, I am facing an issue where the page (html template) is not updating with the controller. It seems like there is a problem in how I've set ...

Is it possible to send back the posted data using res.send after making a post request

I am currently facing a challenge with my post route, where I receive an array of strings from req.body. This array is then used to query my local MySQL database multiple times in order to retrieve specific data that I need to send back to the client (reac ...

Navigating through multiple nested objects to access a specific property

My query involves working with JSON data that I have stored within a specific variable. This is the JSON content: {"json":{"-K-dxZZVLv4N11BQ-tEJ":{"AssetID":1},"-K-dxwm5y1hVS68GyMhN":{"AssetID":2}}} Below is my attempt: var url = "https://rbxjson.fireb ...