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

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

What is the best way to implement a composite primary key in DocumentClient.batchWrite()?

I am attempting to conduct a batch delete process based on the instructions provided in this documentation. The example given is as follows: var params = { RequestItems: { /* required */ '<TableName>': [ { DeleteRequest: ...

Having trouble with jQuery UI draggable when using jQueryUI version 1.12.1?

Currently, I am diving into the world of jQuery UI. However, I am facing an issue with dragging the boxes that I have created using a combination of HTML and CSS. My setup includes HTML5 and CSS3 alongside jQuery version 1.12.1. Any suggestions or help wou ...

Having trouble with protractor's sendKeys function when trying to interact with md-contact-chips

Does anyone know how to set a value using sendKeys in Protractor for md-contact-chips? I attempted to use element(by.model('skills')).sendKeys('Java'); but it doesn't seem to be working. Any suggestions on how to approach this in ...

Align the timing of the animation with the dataset in ThreeJS

I am faced with the challenge of working with data that includes time in milliseconds and the x, y, z position of an object at each specific time interval. msec |pos_x |pos_y |pos_z ------------------------------ 0 |318 |24 |3 25 |3 ...

Changing the size of icons in an Alert using Material UI with React

Recently, Material UI unveiled the new 'Alert' component. Everything seems to be working well, except for the fact that I can't find a way to adjust the size of the icon. Here is my code snippet: <Snackbar open={true}> <Alert ...

What are the steps to initiate a new project using the CLI on a Linux operating system

I've got a project up and running in Vue JS with Node JS installed. Now I want to create a new project using CLI. Do I need to install another version of Node JS for this new project? ...

Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$f ...

Utilize the power of Request.JSON to send an HTML array as a post

I have a piece of HTML code that includes form elements: First name: <input type='text' name='first_name' value='' /><br/> Last name: <input type='text' name='last_name' value='' / ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

Acquiring the API through the callback function within a React application

I wrote a function that connects to an API and fetches data: import {API_KEY, API_URL} from "./constants"; export const getOperations = async (id, successCallback) => { try { const response = await fetch(`${API_URL}/tasks/${ ...

I am encountering an issue where the span does not display when I click the button in Vue.js. I am seeking advice on how to troub

I am having an issue with conditional rendering in Vue.js. When I click on the button, the span does not render as it should. How can I resolve this issue? <v-btn icon @click="showInfo = !showInfo"> <v-icon>mdi-dots-vertical&l ...

Extract the content from a <Span> element without specifying its ID

Is there a way to make it so that when a user clicks on an HTML tag, the text is copied to their clipboard? I also need to ensure that this functionality does not apply to a specific tag ID/name as I am unable to add those to my span. Is there a way to aut ...

Oops! It seems like you've stumbled upon a 404 error on Django

I need to retrieve the price value immediately after a product is selected in the sale form. The sale form includes fields for price, quantity, and product. Once a user selects a product, the price of that product should populate the input box for price. T ...

Calculate the combined sum of values within dynamic inputs that share a common class, and automatically update the sum whenever input values are altered or new rows are added or removed dynamically

$("#add-btn").click(function() { $("#dynamic").append('<tr>' + '<td class="td">' + '<input type="number" name="Debit" class="form-control Debit"/>' + '</td>' + '<td c ...

PhoneGap Troubleshooting: Device Plugin Malfunctioning

I'm having trouble getting the device plugin to work with my Cordova/PhoneGap project. Currently, I am using Cordova version 3.3.1-0.1.2. I followed the documentation and installed the plugin using the following command: C:\ProjectFolder>pl ...

Display a loading spinner until all child components within a Page have finished rendering in Nativescript

I need to display an activity indicator when transitioning from one page to another, but the destination page has multiple components that take time to load. I am looking for a way to detect when all child components are loaded so that I can update my vari ...

Occasionally, the array of image icons fails to load, but this issue is

Currently, I am encountering an issue where my app icons are not loading properly on the screen. Most of the time, everything works fine with no errors. However, occasionally (about 1 in 20 times), the icons fail to load as expected, leaving only the app n ...

Is it possible to dynamically insert one module into another module?

Let's say I have 2 modules in two separate files: The first one is for everyone, let's call it myApp: var myApp = angular.module('myApp', ['dependency.one', 'dependency.one']); In another file named admin.js, I ha ...

Node.js data transmission: Sending information from server to client

In my node project, PUG/Jade files are used to render webpages. Every minute, a JS file updates a redis database and I want the GUI to reflect these changes without requiring a page refresh. Here is an overview of how the data is currently passed: User ...