Formulate a fresh JavaScript array by extracting information from the properties of an object

I am looking to transform a flat array containing similar data in separate properties into an array of arrays that groups the data fields from each property together. It might be easier to understand with an example.

The original array:

        [{"MtmDate":"2014-10-24", "MouldingID":"1233B", "ID":38, "Mtm01":5.10, "Mtm02":6.63,"Mtm03":5.84 },
         {"MtmDate":"2014-10-25", "MouldingID":"1233B", "ID":39, "Mtm01":5.13, "Mtm02":6.21,"Mtm03":6.64 },
         {"MtmDate":"2014-10-26", "MouldingID":"1233B", "ID":40, "Mtm01":5.68, "Mtm02":5.95,"Mtm03":6.37 },
...
]

Desired output:

    [{"Mtm": 1, values: [{"MtmDate": "2014-10-24", "ID":38, data: 5.10},
                       {"MtmDate": "2014-10-25", "ID":39, data: 5.13},
                       {"MtmDate": "2014-10-26", "ID":40, data: 5.68}]},
     {"Mtm": 2, values: [{"MtmDate": "2014-10-24", "ID":38, data: 6.63},
                       {"MtmDate": "2014-10-25", "ID":39, data: 6.21},
                       {"MtmDate": "2014-10-26", "ID":40, data: 5.95}]},
     {"Mtm": 3, values: [{"MtmDate": "2014-10-24", "ID":38, data: 5.84},
                       {"MtmDate": "2014-10-25", "ID":39, data: 6.64},
                       {"MtmDate": "2014-10-26", "ID":40, data: 6.37}]},
     ]

I know I can achieve this by manually creating objects for each data field and adding them to the new array:

    var mtm1 = { mtm: 1, values: [] }, mtm2 = { mtm: 2, values: [] }, mtm3 = { mtm: 3, values: [] };
    var dataByPoint = [];
    dataByPoint.push(mtm1);
    dataByPoint.push(mtm2);
    dataByPoint.push(mtm3);

Then by looping through the original array, I can retrieve the data for each object:

$.each(d, function(index, value) {
    var details1 = { mtmDate: value.MtmDate, id: value.ID, data: value.Mtm01 };
    if (details1.data) dataByPoint[0].values.push(details1);

    var details2 = { mtmDate: value.MtmDate, id: value.ID, data: value.Mtm02 };
    if (details2.data) dataByPoint[1].values.push(details2);

    var details3 = { mtmDate: value.MtmDate, id: value.ID, data: value.Mtm03 };
    if (details3.data) dataByPoint[2].values.push(details3); 
});

However, since there are numerous data properties, this method seems cumbersome. Is there a more efficient way to populate the new array by iterating through the data properties?

Answer №1

let objArr =[{"MtmDate":"2014-10-24", "MouldingID":"1233B", "ID":38, "Mtm01":5.10, "Mtm02":6.63,"Mtm03":5.84 },
         {"MtmDate":"2014-10-25", "MouldingID":"1233B", "ID":39, "Mtm01":5.13, "Mtm02":6.21,"Mtm03":6.64 },
         {"MtmDate":"2014-10-26", "MouldingID":"1233B", "ID":40, "Mtm01":5.68, "Mtm02":5.95,"Mtm03":6.37 }
]

let newArr = [];
for (let i = 0; i < objArr.length; i++)
        {
    let newObj = {};
    newObj.Mtm = (i+1);
    newObj.values = [];
        if (Object.keys(objArr[i])[i+3]) //check for 'Mtm##' presence
        {
              for (let j = 0; j < objArr.length; j++)
              {
                   let keys = Object.keys(objArr[j]);
          newObj.values.push({"MtmDate" : objArr[j].MtmDate, "ID" : objArr[j].ID, "data" : objArr[j][keys[i+3]]}); 
       }
        }
    newArr.push(newObj);
}

document.write(JSON.stringify(newArr))

This code snippet uses nested loops to process the data effectively.

The outer loop creates new entries in the array, while the inner loop extracts and arranges the original data elements correctly. It makes use of `Object.keys` to identify and extract the appropriate data element based on the looped index.

Answer №2

Utilizing the map method on an array.

let initialArray =   [{"MtmDate":"2014-10-24", "MouldingID":"1233B", "ID":38, "Mtm01":5.10, "Mtm02":6.63,"Mtm03":5.84 },
         {"MtmDate":"2014-10-25", "MouldingID":"1233B", "ID":39, "Mtm01":5.13, "Mtm02":6.21,"Mtm03":6.64 },
         {"MtmDate":"2014-10-26", "MouldingID":"1233B", "ID":40, "Mtm01":5.68, "Mtm02":5.95,"Mtm03":6.37 },
...
]

let newArray = initialArray.map(function(item){
   return {mtm:item.ID, values:item}
})

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

Creating a collection of related elements

My objective is to convert the values from a for loop into an associative array. //$from_time value is 6 and $to_time value is 23 for ($i = $from_time; $i <= $to_time; $i++) { $working_time_array[] = $i; } echo json_encode($working_time_ar ...

Angular.js' Element.prop('scrollHeight') consistently gives identical values for various list items

I have been attempting to determine the heights and widths of the items in my list. Despite exploring various methods for obtaining the height and width of an item, none of them seemed to provide the scrollHeight directly from the element. Upon inspecting ...

React NextJS: Unable to retrieve cookies or properties post redirection

Within my nextJS application, when a user logs in on the login page, a cookie is created with a token and then they are redirected to the main page which utilizes the main component. However, within the Main component, I am encountering an issue where the ...

Having trouble converting svg to png, thinking it might be due to discrepancies in svg elements

I am facing a puzzling issue where two different SVG elements are causing my JavaScript to work in one scenario but not the other. I have replaced the SVG elements in both examples, and surprisingly, only one works while the other does not. You can view th ...

Update the styling of a CSS div based on certain conditions

Is it possible to have a centered fullscreen main section at the very center of the webpage? <div id="main"></div> The main section will display a default web page: <script> $("#main").html('<object data="http://www.myweb.com"/ ...

Can you provide a require statement that is the equivalent of this import statement?

Looking to transition a few files from utilizing import to using require in order to eliminate the need for Babel. One of the import statements appears like this: import React, { Component } from 'react'; How can I change it to a require state ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

Experimenting with directive using jasmine

I've been working on this directive but I'm having trouble writing the jasmine test for it. Any suggestions? import { Directive, Output, EventEmitter, HostListener } from '@angular/core'; @Directive({ selector: '[ctrlKeys]&apos ...

Finding strikeout text within <s> or <del> tags can be identified by closely examining the HTML codes

The issue arises with the text that reads as follows: 316.6.1 Structures. Structures shall not be constructed This is represented in HTML as: <b> <s> <span style='font-size:10.0pt'>316.6.1 Structures</span> ...

Issue encountered when invoking JavaScript from Angular TypeScript

I'm attempting to invoke a JavaScript function from within a TypeScript function, but it doesn't seem to be functioning properly. I've drafted some pseudo code on StackBlitz. Could you please take a look? https://stackblitz.com/edit/angula ...

Unable to add or publish text in CKEditor

In my ASP.NET MVC application, I am struggling to post the updated value from a CKEditor in a textarea. Here is the code snippet: <textarea name="Description" id="Description" rows="10" cols="80"> This is my textarea to be replaced with CKEditor ...

Navigating through multi-dimensional arrays without prior knowledge of the number of dimensions

I'm currently dealing with data extracted from netcdf files, including multi-dimensional variables that are imported into numpy arrays. My goal is to iterate through all the values in each dimension (referred to as axes in numpy) and make modification ...

The magic of data binding in AngularJS's ng-repeat

Is it possible to dynamically call an attribute of a data-binded object based on the ng-repeat object? I have set up a simple example, but I'm not sure if it can be solved this way. Can anyone help with this? The goal is for the input to receive the ...

nodejs promises and their implementation in loops

Currently delving into the realm of promises in nodejs, here's an example code snippet for you to peruse: The result when running the below code is as follows: test - 1 test - 2 test - 3 test - 4 var Q = require('q'); var promise = Q.when( ...

Retrieve JSON data from a PHP script to be used in an Angular scope

I am attempting to retrieve JSON data from a PHP file to use in an Angular controller. I have used json_encode(pg_fetch_assoc($result)); within the PHP file and when I check with console.log($scope.contents); in the Angular controller, the JSON data is ret ...

Choosing between vm. and this. in Vue.js

My understanding of when to use the "this" keyword in vue.js is a bit cloudy. In the example below, whenever I replace "this" with "vm", the code stops functioning. I have come across instances where "self" was used instead of "this", but as someone who i ...

Difficulty in decoding intricate JSON response using JQuery (or simply JavaScript)

Consider the function below, which retrieves JSON data from a Solr instance: var url = "http://myserver:8080/solr/select?indent=on&version=2.2&q=(title:*Hollis* OR sub_title:*Hollis*+OR+creator:*Hollis*+OR+publisher:*Hollis*+OR+format:*Hollis*++OR ...

What is the best way to connect a jQuery event to a function within an object?

I've been working on defining an object with properties and methods, but I'm facing some difficulty in attaching a jQuery function to a method. What I aim to achieve is that when I click on the object #myTarget, it changes its HTML text. My curr ...

What is the process for removing a registered user from Realm Object Server with the use of the Javascript library?

I have been searching online for a solution, but I haven't been able to find an answer. I am attempting to remove a user from ROS, however, I cannot locate a designated API for this task. The version of my realm-js is 1.10.3. If this feature does not ...

Can the manifest.json file be edited dynamically?

I'm in the process of developing a React PWA and I'm exploring the possibility of dynamically adding icon URLs to the manifest.json file. My aim is to display a generic app icon until the user logs in. Once logged in, I plan to fetch a new icon f ...