Minimize and dismantle the object deconstruction/allocation

Imagine I have two basic objects and I want to combine their properties to create a third object. It works smoothly with this code:

(()=>{
  const firstObj = {a: 2, b: 3}
  const secondObj = {a: 100, c: 5}
  return {...firstObj, ...secondObj}
})()
// { a: 100, b: 3, c: 5 }

However, things get tricky when I attempt to use .reduce to create a new object based on secondObj. To keep it simple, let's say we have a reduce function that simply clones the secondObj:

let result = (()=>{
  const firstObj = {a: 2, b: 3}
  const secondObj = {a: 100, c: 5},
  cloneObj = Object.entries(secondObj).reduce((acc, [key, value])=>Object.defineProperty(acc, key, {value}), {})
  console.log(cloneObj) // {a: 100 c: 5}
  return {...firstObj, ...cloneObj}
})()
console.log(result);// { a: 2, b: 3 }

I have a suspicion that my understanding of the .reduce function is lacking. How can I solve this issue?

Answer №1

By default, attributes made using defineProperty are not counted, thus they will not be spread out.

To resolve this:

b2 = Object.entries(b1).reduce((acc, [key, value]) =>
  Object.defineProperty(acc, key, {value, enumerable: true})
, {})

Answer №2

Make sure to set the property as enumerable.

Object.defineProperty(acc, key, {value, enumerable: true});

Instead of the above step, you could simply use Object.assign function for a more straightforward approach.

let x = (()=> {
  const obj1 = {a: 2, b: 3};
  const obj2 = {a: 100, c: 5};
  const obj3 = Object.entries(obj2).reduce((acc, [key, value]) => Object.assign(acc, {[key]: value}), {})
  console.log(obj3); // {a: 100 c: 5}
  return {...obj1, ...obj3}
})()
console.log(x); // { a: 2, b: 3 }

Answer №3

To address this issue, consider utilizing Object.assign to clone the object b1 as shown below:

let r = (()=>{
  const a1 = {a: 2, b: 3}
  const b1 = {a: 100, c: 5}
  const b2 = Object.assign({}, b1)
  console.log(b2) // {a: 100 c: 5}
  return {...a1, ...b2}
})()

console.log(r); // { a: 100, b: 3, c: 5 }

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

Ways to achieve 8 columns in a single row using Javascript and Bootstrap

Recently, I created a simple function for searching movies and manipulating them in the DOM. The issue arises when a movie name is entered and the API response returns around 20-30 recommendations. I wanted to display this fetched data in 8 columns per row ...

Converting images to greyscale or transparency within a ReactJS component

I am exploring ways to transform an image into grayscale or make it transparent before using it as a background in ReactJS. Is there a way to achieve this in ReactJS? My current code snippet is shown below: <GridListTile> <img style={{ -we ...

Parse JSON files from a folder and concatenate them to a CSV using Node.js

Thank you for offering your help. I have a collection of JSON files located in a directory with unknown names. I need help with the following: (1) Reading all the JSON files (2) Appending the data from the JSON files to output.csv (3) Adding "-Appended" t ...

Adding data to a multidimensional array in JavaScript

I am in need of creating a multidimensional JavaScript array dynamically, following this specific structure: array_answers[0][1]:"yes" array_answers[1][2]:"no" array_answers[2][2-subquestion]:"text input" array_answers[3][8]:"yes" array_answers[4] ...

Click to dynamically change the input number variable

I'm in the process of creating a special calculator, where you input the number of years into a field, hit submit, and see different results displayed below without the page reloading. All my calculations are working properly at the moment. However, ...

Using JavaScript and HTML, showcase the capital city of a country along with its corresponding continent

As a newcomer to this platform, I am excited to share a code snippet that I have created using HTML and JavaScript. The code generates a textbox in an HTML page where users can type the name of a country. Upon inputting the country's name, the code dy ...

Enhancing JavaScript Variables Through Dynamic Ajax/PHP Interaction

I've been encountering some difficulties when trying to refresh my game. Initially, I attempted echoing the entire script each time... but that method was not aesthetically pleasing. Currently, I am experimenting with updating the variables through an ...

Why does my console refuse to log the input entered for the search?

Looking to become proficient in web development, I am attempting to record HTML search queries in the console after storing them in a variable. However, when I try running the search procedure, nothing seems to be displaying in my browser's inspect co ...

Error message "Uncaught TypeError: Unable to read property 'defaultView' of undefined" was encountered while using Google Maps

I am encountering an issue when attempting to load a Google map in React: "Uncaught TypeError: Cannot read property 'defaultView' of undefined" The problem seems to be isolated within this particular component, as the rest of the app renders su ...

Exploring Antialiasing Techniques in Three.js

Our team is currently working on constructing a 3D room filled with various objects and furniture, all to be showcased on a large flat screen. Despite utilizing the fxaa-shader due to other effects we're implementing, the results have been less than s ...

Guide on how to retrieve additional data from the API by pressing the "Load More" button

Hello, I am working on a project where I aim to display user data from an API called https://reqres.in/api/users?page=(the page number can be 1,2 or more) and present it in an HTML table using JavaScript with promises. Currently, I have successfully popula ...

Setting compilerOptions.isCustomElement for VueJS 3 in a Laravel project: A step-by-step guide

I am currently working on integrating VueJS 3 into a Laravel project and utilizing a JS file to implement a markdown toolbar. The JS file contains functions that generate buttons for applying various markdown options. Everything is functioning properly, bu ...

Utilize a traditional JavaScript class to instantiate an object in Vue.js

Is it possible to integrate a standard JavaScript class into a Vue.js component without needing anything static? If not, I am open to switching to React or Angular. Are they more suitable than Vue.js for code reusability? Test.js file: class Test { co ...

What is the best way to bring a string into my .tsx file using a relative reference from a module?

I am currently developing an online course on creating a website using StencilJS, NodeJS, and the IonicFramwork. As a newcomer in this field, I have encountered a challenging issue: In my project, the API "https://swapi.dev/api" is imported as a ...

"Experience the power of Angular.js through seamless animations created by blending the capabilities

I want to smoothly fade out the old view and fade in the new view. The challenge is that the new content must be positioned absolutely until the old one fades out. I also want to set a specific top position and height for the new content, but when I try to ...

Choosing a specific element through its CSS selector in Puppeteer

I'm currently working on selecting an image element using its style selector. Initially, I successfully wrote the code in Python, but I seem to be encountering some difficulties while trying to translate it to JavaScript. Below is my progress so far. ...

Tips for Quickly Filtering a Large JSON Dataset in ReactJS

I am currently working with a large JSON dataset that looks something like this: [ {"date":"2020-03-02", "state:"Delhi", "district":"East Delhi" ..... ..... } ..... ..... ] I have a variety of filters avail ...

What is the best way to send a request in a route and wait to return a response until the data is ready?

I've been advised to utilize axios for making API requests, but I'm encountering the issue of it being asynchronous and responding before the inner POST request is fully completed: var express = require('express'); const axios = require ...

How can we deliver pure JS, HTML, and CSS content without relying on static HTML pages?

Looking to create a fast app prototype without using React or Vue? I'd like to avoid simply making an html and js file imported within it. Can npm packages, SCSS be used while programming vanilla Javascript minus a framework? ...

Utilize npm node to dynamically adjust screen resolution

Currently developing a game using electron. I'm experiencing FPS drops when running it in full-screen mode. To improve the game's performance, I need to change the screen resolution programmatically. My current resolution is 1280x800, but I would ...