Transform a JavaScript object array into a collection of individual values

Given a list of objects structured like this, I am looking to transform it into a list of values based on their corresponding IDs.

Original = [
    {id: 1, value: 12.2494, time: "00:00:00.14"},
    {id: 1, value: 4.5141, time: "00:00:01.138"},
    {id: 1, value: 2.85930, time: "00:00:02.138"},
    {id: 1, value: 1.0364, time: "00:00:03.146"},
    {id: 2, value: 4.3510, time: "00:09:15.157"},
    {id: 2, value: 3.90, time: "00:09:16.115"},
    {id: 2, value: 3.544, time: "00:09:17.116"},
    {id: 2, value: 3.247, time: "00:09:18.157"}
]

Desired outcome

data[1]={value:[12.494, 4.5141...],time: ["00:00:00.14","00:00:01.138"]...} 
data[2]={value:[4.3510, 3.90...],time: ["00:09:15.157","00:09:16.115"]...}

In attempting this transformation, I encountered an issue where only one value was being returned:

var data= {};
original.forEach(function(item) {
    var id = item.id;
    data[id] = {
        value:[],
        time:[]
    }
    data[id].value.push(item['value']);
    data[id].time.push(item['time']);
})

Answer №1

To achieve this functionality, you can utilize the reduce function available in Arrays.

Firstly, you need to check the current id within the accumulator;

If the id already exists, push the values and times to the stored arrays.

Otherwise, create a template object and populate it with the values and times.

var Original=[{id: 1, value: 12.2494,  time: "00:00:00.14"},{id: 1, value: 4.5141, time: "00:00:01.138"},{id: 1, value: 2.85930,  time: "00:00:02.138"},{id: 1, value: 1.0364,  time: "00:00:03.146"},{id: 2, value: 4.3510,  time: "00:09:15.157"},{id: 2, value: 3.90, time: "00:09:16.115"},{id: 2, value: 3.544, time: "00:09:17.116"},{id: 2, value: 3.247,  time: "00:09:18.157"}];

var data = Original.reduce((a, c) => {
  var current = (a[c.id] || (a[c.id] = {value: [], time: []}));
  current.value.push(c.value);
  current.time.push(c.time);
  
  return a;
}, {});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you prefer not to use the push method due to a personal preference, there's an alternative approach you can take:

const original = [
    {id: 1, value: 12.2494, time: "00:00:00.14"},
    {id: 1, value: 4.5141, time: "00:00:01.138"},
    {id: 1, value: 2.85930, time: "00:00:02.138"},
    {id: 1, value: 1.0364, time: "00:00:03.146"},
    {id: 2, value: 4.3510, time: "00:09:15.157"},
    {id: 2, value: 3.90, time: "00:09:16.115"},
    {id: 2, value: 3.544, time: "00:09:17.116"},
    {id: 2, value: 3.247, time: "00:09:18.157"}
]

const data = original.reduce((x, y) => x[y.id]
    ? Object.assign({}, x, {
        [y.id]: {
            value: x[y.id]
                .value
                .concat(y.value),
            time: x[y.id]
                .time
                .concat(y.time)
        }
    })
    : Object.assign({}, x, {
        [y.id]: {
            value: [y.value],
            time: [y.time]
        }
    }), {})

Alternatively, if your data contains gaps and you want to avoid adding undefined values, you can follow this procedure:

const unoriginal = [
    {id: 1, value: 12.2494, time: "00:00:00.14"},
    {id: 1, value: 4.5141, time: "00:00:01.138"},
    {id: 1, value: 2.85930, time: "00:00:02.138"},
    {id: 1, value: 1.0364},
    {id: 2, time: "00:09:15.157"},
    {id: 2, value: 3.90, time: "00:09:16.115"},
    {id: 2, value: 3.544, time: "00:09:17.116"},
    {id: 2, value: 3.247, time: "00:09:18.157"}
]

const otherData = unoriginal.reduce((x, y) => x.includes(y.id)
    ? x
    : x.concat(y.id), []).map(x => Object.assign({}, {
    [x]: {
        value: unoriginal
            .filter(y => x === y.id)
            .reduce((z, a) => a.value
                ? z.concat(a.value)
                : z, []),
        time: unoriginal
            .filter(y => x === y.id)
            .reduce((b, c) => c.time
                ? b.concat(c.time)
                : b, [])
    }
})).reduce((x, y) => Object.assign.apply(null, [x].concat(y)))

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

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

Is there a way to transfer PHP user information (session) to a Node.js server?

Currently, I have two separate pages set up for my website. One is the Chat page, which operates on Node.js and Socket.io using WebSockets. The other is the main page where users login and access various features. I am looking to implement a system where, ...

Utilizing Header and Footer Components in React JS

I'm new to Reactjs(Nextjs) and I am looking to create a "header" and "footer" file that can be used on all pages. I would like to know the best approach to achieve this. Should I create a "Layout.js" file and then call the Header within it? Or should ...

Seeking to duplicate script for a new table without making any changes to the original script

I am working with two tables that require the capability to dynamically add and delete rows using separate scripts. How can I modify the second script so that it only affects the second table and not the first one? Table: <table id="myTable" class=" t ...

Modifying a Nested Component with react-icons

As I work on creating a rating component that utilizes react-icons to display icons, I have encountered an interesting challenge. Currently, I am using the FaStarhalf icon which represents a pre-filled half star that can be flipped to give the appearance o ...

Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types. In the Blade file Ad ...

Two distinct controllers: concealing elements through the operation of one of them

I am facing a challenge with my HTML elements: In one form-group, I have the following input: <div class="form-group"> <input type="search" ng-model="search"/> </div> This particular form-group needs to be hidden when another form-g ...

Including an <a> tag within a JavaScript variable to utilize in an HTML statement

I want to wrap an <a> element around a JavaScript variable containing a string. The desired output should be the 'copyright symbol' followed by the 'companyName' linked as an HTML link and then the current year's date. JavaS ...

Ways to monitor and measure clicks effectively

Within my website, I have a table element with one column and numerous rows. Each row serves as a hyperlink to an external shared drive. <tr><td ><a href="file://xxx">Staff1</a></td></tr> <tr ><td ><a h ...

Adjusting canvas size to match content dimensions

I posed a similar inquiry and it was categorized as a duplicate even though the suggested duplicate did not provide an answer to my question. Edit: The purported duplicate was [stackoverflow.com/questions/17211920/make-canvas-height-auto][1] I am utilizi ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...

AngularJS ng-show will not function properly with newly added DOM elements

I am encountering an issue with ng-show directives on dynamically added DOM elements in AngularJS. The directives work fine when the page initially loads, but new elements that are added later do not have their expressions evaluated. Is there a way to prom ...

To prevent the animation from overflowing, set the parent element to have hidden overflow while still displaying the child element

I am facing an issue with two menus that can be toggled using a switch. Each menu item has a dropdown that appears when clicked. The problem arises when switching between the menus, as there is an animation for the transition (slide in and slide out). I wa ...

Delete an <li> element upon clicking a span tag

I've been attempting to fadeOut some <li> elements, however I haven't had any success. Here's my code below: <li class="lclass" id="1"> First Li <span class="removeit" id="1" style="color:#C00;">Remove</span> ...

Show informational pop-up when hovering over selected option

My goal is to create an information box that appears when a user hovers over a select option. For example: <select id = "sel"> <option value="sick leave">Sick leave</option> <option value="urgent leave">Urgent lea ...

Could offering a Promise as a module's export be considered a legitimate approach for asynchronous initialization in a Node.js environment?

I am in the process of developing modules that will load data once and create an interface for accessing that data. I am interested in implementing asynchronous loading of the data, especially since my application already utilizes promises. Is it considere ...

Determine whether a directive possesses a specific attribute

Here is my current code snippet: <my-directive></my-directive> I am trying to include a ternary operation within it like this: {{ $scope.my-option ? 'YES' : 'NO' }} Is it possible to achieve the desired result by adding ...

Is it possible in Angular to generate a module and component without including a CSS file in a single command?

Is it possible to generate a Module linked to a component without automatically creating a css file? For example, the default method I've been using involves: ng generate module name / ng generate component name This results in the typical componen ...

Animated smooth updates in d3 line graphs are the key to creating dynamic and

I'm attempting to modify an example of Animated Line Graphs from: http://bl.ocks.org/benjchristensen/1148374 <div id="graph1" class="aGraph" style="width:600px; height:60px;"></div> <script> function draw(id, width, height, upd ...

Utilizing jQuery to Adjust Tab Transparency

I'm trying to add some opacity to my jQuery tabs, but so far I've only been successful with accordions. Any tips or tricks for achieving this effect with tabs? Styling with CSS .ui-tabs{ background-image: none; background: rgba(204, 204 ...