JavaScript ES6 array method for generating an object from an array

I wish to transform the following array:

[
  { 
    event: "LIB",
    block_calendar: "YES",
    obs: "Lorem Ipsum",
    status: "Block",
  },
  { 
    event: "LIB"
    block_calendar: "YES"
    obs: "Ipsum Lorem"
    status: "Block"
  }
]

into this object

{
  event: "LIB",
  obs: ["Lorem Ipsum","Ipsum Lorem"]
}

Is there an ES6 method or approach that can achieve this transformation?

Answer №1

You can utilize the Array#reduce method to accumulate an object containing the desired data. Iterate through each object in your array and check if the accumulated object has an entry for the specified key. If it does not exist, create it with the necessary properties initialized (e.g., event and obs as empty arrays). Then, add the corresponding obs-value to this array.
To extract the desired array from this structure, you can use Object#values to eliminate the outer grouping level.

Please note: The problem has been generalized slightly to allow for different events to be grouped together.

let arr = [
  { 
    event: "LIB",
    block_calendar: "YES",
    obs: "Lorem Ipsum",
    status: "Block",
  },
  { 
    event: "LIB",
    block_calendar: "YES",
    obs: "Ipsum Lorem",
    status: "Block"
  }
];

let result = Object.values(arr.reduce((acc, cur) => {
    if (!acc[cur.event]) 
        acc[cur.event] = {event: cur.event, obs: []};
    acc[cur.event].obs.push(cur.obs);
    return acc;
}, {}));

console.log(result);

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

HTML code displaying a fixed message at the top of the webpage

I'm working on a web page that has a lot of content. I need to have a message always visible at the bottom of the browser window, even when scrolling. Can anyone help me achieve this using simple CSS, HTML, jQuery, or PHP? Thanks! ...

Encase all jQuery functionalities within a custom class

I am looking to create a JavaScript class that encapsulates jQuery's DOM functions, but I want these functions to only interact with a single property of that class. class Foo { constructor() { this.$wrapper = $('<div>wrapper</div ...

Encountering JSON error when invoking multiple functions

Encountering JSON Error when calling multiple functions Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0 I've been attempting to call multiple functions in jQuery but keep getting an error. I've tried various soluti ...

The Print Preview Displays No Content When an External Stylesheet Reference is Included in the Printable HTML Content

Is there a way to print the contents of a DIV on a webpage? Currently, I am using JavaScript to retrieve the contents of the div and then passing it to a new window object where I call the .print() function. The text contents and images are displayed corre ...

Issues with Javascript functionality on aspdotnetstorefront site

Lately, I've been facing some challenges with my Javascript and jQuery codes when trying to implement them in the storefront. Despite attempting different methods to create a slider, none seem to work within the store environment - even though they fu ...

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...

What is the best way to link the data from the HTML input to the class property in the TypeScript file? (Combining Angular and IntroJs)

I'm working on an onboarding screen with Intro.js and need help with receiving user input. I've been trying different methods like [(ngModel)] = checked, [(checked)] = checked, (checked) = checked, but haven't had any success. Can anyone pro ...

Keys in React Native's ListView are used to uniquely identify

There is a warning in my app that is causing me some concern. React keeps prompting me to add keys for each row, but no matter what I try, I can't seem to include these keys. This is how my code looks: <ListView style={styles.listView} dat ...

The Click Event Is Triggering Even with Correct Callbacks Being Set

I am struggling to understand why these functions are not executing properly. I know the correct syntax for binding a function, like this: $('#idOfThing').bind('click', foofunc); function foofunc() { ///do things } However, I am facin ...

Axios delivers the index.html data to the front end of a React.js application

I’m currently in the process of developing a web application using React.js for the front-end and Flask for the back-end. I attempted to establish a connection between the two by defining a proxy server in React and enabling CORS in Flask. Everything was ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

Utilize a pre-defined layout in a Vue component that is sent as a property

As a complete beginner, I kindly ask for your patience as I navigate through the coding basics. I am looking to utilize a template specified in the prop. The template is located within the DOM. My intention for approaching it this way is to reuse the comp ...

Right now, I am sending out 3 GET requests for JSON files using Axios. I wonder if they are being loaded simultaneously or one after the other

In the process of developing my application, I am loading 3 JSON files to gather information about a game's characters, spells, and more. As of now, I have implemented 3 functions that utilize axios to make GET requests and store the responses. Howeve ...

Combining objects using Vue.js and Axios

After fetching data from an axios request and a fetch call to an RSS feed, I have two objects with fields that serve the same purpose but have different names. See the example below: Two Object The objects currently look like this: Obj1 = {title: "Main te ...

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

I encountered a problem with React Native while attempting to update the state with a new value

As I work on developing my app using react native and firebase, I encountered an issue with the error message TypeError: undefined is not an object (evaluating 'this.state.desativado.push') when attempting to click the + button. For the complete ...

Passing layout to a Vue component using the setup script

LayoutComponent <template> //some code here ... <div> <slot></slot> </div> </template> In the composition api, it is possible to pass a layout by importing it and then passing it into t ...

Removing all Null Form Inputs from the Document Object Model upon Submission utilizing JavaScript

I am currently working on a conditional Shopify form that was passed down to me from another developer. The form utilizes JavaScript/Jquery for field validation, ensuring that all mandatory fields are completed before proceeding to the next step. After mak ...