transform array elements into an object

I encountered the following code snippet:

const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map(
        (cssClass) => {
          return { [cssClass]: true };
        }
      );

This code block generates an array of objects like this:

{ "custom-calcrow-1": true },
{ "custom-calcrow-2": true }

Now, I have a base object structured as follows:

{ "calcrow": true}

The main question here is how can I append the above two entries to the existing object so that the final output will look like this:

{
  "calcrow": true,
  "custom-calcrow-1": true,
  "custom-calcrow-2": true
}

Essentially, my goal is to merge an array of objects into one. However, using the current approach such as

return { calcrow: true, ...calcRowCssClasses };

results in:

0: {custom-calcrow-1: true},
1: {custom-calcrow-2: true},
calcrow: true

This outcome does not align with the desired expectation.

Your input and guidance are appreciated.Thank you!

Answer №1

If you want to merge objects in JavaScript, one way to do it is by using Object.assign along with spreading the array as parameters.

return Object.assign({ calcrow: true }, ...calcRowCssClasses);

const calcRowCssClasses = [
    { "custom-calcrow-1": true },
    { "custom-calcrow-2": true }
];

const originalObject = { calcrow: true };

const result = Object.assign(originalObject, ...calcRowCssClasses);

console.log(JSON.stringify(result, null, 4));

Answer №2

Why not try using Array.prototype.reduce instead of .map()? It can be a more efficient solution.

const context = {dataItem: {cssClasses: ["custom-calcrow-1","custom-calcrow-2"]}};

const calcRowCssClasses = context.dataItem.cssClasses.reduce((ob, cssClass) => (ob[cssClass] = true, ob), {});

console.log({calcrow: true, ...calcRowCssClasses});

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

Ensuring precise type inference in generic functions using the keyof keyword

I am facing a challenge in creating a versatile function that accepts an object and a key from a specific subset of keys belonging to the type of the object. These keys should correspond to values of a specified type. This is how I attempted to implement ...

Experiencing issues with the functionality of jQuery AJAX?

I am experiencing difficulties with a jQuery AJAX post. Here is the code: <script> var callback = function(data) { if (data['order_id']) { $.ajax({ type: 'POST', url: '<?php echo $_SERV ...

Data in DynamoDB Local is deleted once the instance is shut down

My app is utilizing DynamoDB Local and I am facing an issue where it keeps deleting all the sample data each time I shut down the instance. This problem seems to be unique as I have not found any similar cases while searching for a solution. I typically ...

Is the background color change function with AJAX not functioning properly when using array values?

Let me simplify my issue. I have an AJAX call to fetch a JSON array with "aht_value". Based on this value, I am creating a color gradient from green to red (creating a heat map). The values are being output correctly. The issue: The problem lies within m ...

Run a Python function in Django without any feedback

Currently, I am utilizing Django for a project and I find myself in a situation where I need to carry out certain functions based on user input. If the action requires displaying new values, I know how to handle that. However, when I simply need to execute ...

When the phone locks, Socket.io experiences a disconnection

setInterval(function(){ socket.emit("stayalive", { "room": room }); }, 5000); I have developed a simple browser application with an interval function that is currently running on my phone. I am using Chrome on my Nexus 4 for debugging purposes. However, ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

What is the best way to render a view, hide parameters from the URL, and pass data simultaneously?

In order to display the current view: statVars["sessions"] = userSessions; res.render("statsSessions", statVars); Nevertheless, I must find a way to hide the URL parameters from showing up in the browser's address bar (these parameters are sourced ...

Automatically shutting windows using jQuery after a certain number of seconds

I am currently trying to find a solution to this issue. The problem I am facing is that I need to close a window after it has been open for 7 seconds each time. I have managed to make the windows close using SetInterval, however, the timing is not precise ...

Understanding information in Backbone.js

I have multiple backbone models with nested sub-models. Here's how I've approached the solution: Models.Base = Backbone.Model.extend ({ relatedModels: {}, /** * Parses data based on the list of related models. * * @since ...

What's the reason for not being able to customize classes for a disabled element in Material-UI?

Currently, I am utilizing Material-UI to style my components. However, I am facing challenges when trying to customize the label class for disabled buttons. Despite setting a reference as "&$disabled", it does not yield the desired results. import Rea ...

Encountering the issue of "Unknown provider" while injecting Angular modules

After following a tutorial on organizing an Angular project, I came up with a structure where I have a ng directory containing all my controllers, services, and the routes.js file. These are then bundled together into an app.js through my configuration in ...

Ensure to verify the input's value by clicking the button

Upon clicking a button, I am trying to determine if there is any content in an input field. However, it seems that the check only happens once when the website first loads. Subsequent clicks of the button do not detect any new input values entered into the ...

Currency symbol display option "narrowSymbol" is not compatible with Next.Js 9.4.4 when using Intl.NumberFormat

I am currently utilizing Next.JS version 9.4.4 When attempting to implement the following code: new Intl.NumberFormat('en-GB', { style: 'currency', currency: currency, useGrouping: true, currencyDisplay: 'narrowSymbol'}); I ...

Guide on how to reference the Html directory using the path module in Node Js

Desperately trying to send an html file as a response using express, but I'm having trouble locating the position or path of the index.html file. This is how my files are structured - MyWebsite Html index.html Css index.css ...

When a React Native TextInput is focused, it restricts the ability to press other child components

Issue with Nested TextInput component affecting onPress function of other components. Press only works when the TextInput is not in focus. React Native Version : 0.66.3 Here's the code snippet: export const Component = (props): JSX.Element { const ...

Running JavaScript code when the route changes in Angular 6

Currently, I am in the process of upgrading a website that was originally developed using vanilla JS and JQuery to a new UI built with Angular and typescript. Our site also utilizes piwik for monitoring client activity, and the piwik module was created i ...

Why does TypeScript keep throwing the "No inputs were found in the config file" error at me?

Why am I receiving the No inputs were found in config file error from TypeScript? I have set up my tsconfig.json in VS Code, but the error occurs when I try to build it. The terminal displays: error TS18003: No inputs were found in config file '/Use ...

Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm r ...

Checking for offline status in a Cordova app using Angular

I have implemented the following code to determine whether my Cordova application is online or offline. var networkState = navigator.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown'; states[Connection.ETHERNET] = ' ...