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

Determine if a SQL column exists following a SELECT statement

I have a query that I need help with: let selectQuery = "select * from mainTable where username = '"+ username + "'"; In my code, I am trying to make sure that childtable2id exists in the table. Here is what I have so far: for (let i = 0; i & ...

Emphasizing the date variable within a spreadsheet

Hey there! I'm struggling with the code below: <html> <head> <title>highlight date</title> <style> .row { background-color: Yellow; color:blue; } </style> <script type="text/javascript"> </script> &l ...

What is the significance of the source element in Vue3's audio element?

Playing mp3 files works in Vue 2, but not in Vue3. <template> <audio src="../file_example_MP3_700KB.mp3" controls ></audio> </template> In Vue3, the code needs to be modified as follows: <template> <audi ...

What is the importance of using getters for functions involving Moment.js in vueJS and typescript?

weekOfMonth() calculates the current month and week within that month. <template> <h3>{{ weekOfMonth }}</h3> </template> <script lang="ts"> export default class HomeView extends Vue { const moment = require(& ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

Discovering the oldest date in an array with JavaScript

Is there a way to identify the earliest date, also known as the minimum date, within an array using JavaScript? For instance: ["10-Jan-2013", "12-Dec-2013", "1-Sep-2013", "15-Sep-2013"] The desired output would be: ...

Using Selenium Webdriver to set a cookie with a Chrome extension

I have been experimenting with a Chrome extension in order to set a cookie when I use a Selenium Webdriver instance to open a page. Despite trying various methods suggested on different Stack Overflow posts, none of them seem to work as the cookie does not ...

Error suddenly appeared when trying to serve a previously functional project locally: Firebase function module not found

After not making any changes to my firebase-related files, I suddenly started encountering the following issue that I just can't seem to figure out: We were unable to load your functions code. (see above) - It appears your code is written in Types ...

React Component: Issue with toggle functionality in child component not meeting expectations

I'm currently working on a checkbox user interface, where I need to pass a toggle function down to a list component. The issue I'm facing is that while I can check the checkbox successfully, I'm unable to uncheck it for some reason. Below i ...

The hyperlink in the mobile version of the mega menu is unresponsive in HTML

I am encountering an issue with the navigation menu on my Laravel website. The menu links work correctly on the desktop version, but none of the anchor tag links are functioning properly on the mobile version. HTML <div class="menu-container"> < ...

mongodb is experiencing issues with the findOneAndUpdate operation

Below is the code snippet for updating the database. let profileUrl = 'example' UserSchemaModel.findOneAndUpdate({_id:userId}, {$set: {profileUrl:profileUrl} }, {new:true}) .then((updatedUser:UserModel) => { console.log(updatedUser.profil ...

Exploring ways to query a mapped array in React Native

Struggling to search a mapped list in react native? While using a Flatlist would be easier, this task is currently causing me major frustration. If anyone has any insights or solutions, please share them! Here's a snippet of the code: import React ...

Enhance Form within React Calendar

I have developed a calendar using React and Redux. When I click on an empty date, a modal pops up allowing me to add an event. However, I am struggling to implement the functionality to edit that event by clicking on it later. Can someone guide me on the c ...

What is the best way to extract a JSON object from a website search using getJSON or similar techniques?

Can anyone provide guidance on utilizing .getJSON() to access JSON-encoded information from a website that is being searched? I've implemented a Google Custom Search API for my site with the aim of retrieving the JSON file from the search results. Fo ...

What should be the output when ending the process using process.exit(1)?

I need to update my code by replacing throw new Error('Unknown command.') with a log statement and process.exit(1);. Here is the example code snippet: private getCommandByName = (name: string): ICommand => { try { // try to fetch ...

V-Calendar is not displaying the accurate dates

https://i.stack.imgur.com/zk4h7.png The image displays dates starting on June 1, 2022, which should be a Wednesday but appears as a Sunday on the calendar. This issue affects all months as they start on a Sunday instead of their respective weekdays. The p ...

Guide on uploading files using Vue.js2 and Laravel 5.4

I'm currently attempting to implement an image upload feature using Laravel for the backend and Vue.js2 for the frontend. Here are snippets from my code: addUser() { let formData = new FormData(); formData.append('fullname', this.n ...

We encountered a ReferenceError stating that 'dc' is not defined, despite having already imported d3, dc, and crossfilter in

In my current angular project, I have included the necessary imports in the component.ts file in the specific order of d3, crossfilter2, dc, and leaflet. Additionally, I have added the cdn for dc-leaflet.js in the index.html file. Despite these steps, wh ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Does TypeScript lack awareness of type checking within nested functions?

Currently, I am using TypeScript with React and encountering a particular issue. Below is a function I have created to ensure that the variable 'arr' is an Array and not empty. export const isNotEmptyArr = (arr?: unknown[]) => { return Arra ...