What is the most efficient method to convert objects array A to objects array B using JavaScript?

Here is an example of object array A:

[
    {
        "Timestamp": "2015-10-01 00:00:00",
        "Label": "Voltage",
        "Value": "230.12"
    },
    {
        "Timestamp": "2015-10-01 00:00:00",
        "Label": "Frequency",
        "Value": "50.12"
    },
    {
        "Timestamp": "2015-10-01 00:00:00",
        "Label": "Power",
        "Value": "23"
    },
    {
        "Timestamp": "2015-10-02 22:22:22",
        "Label": "Voltage",
        "Value": "231.12"
    },
    {
        "Timestamp": "2015-10-02 22:22:22",
        "Label": "Frequency",
        "Value": "51.12"
    },
    {
        "Timestamp": "2015-10-02 22:22:22",
        "Label": "Power",
        "Value": "23.4"
    }
]

I am looking to transform this into object array B like so:

[
    {
        "Timestamp": "2015-10-01 00:00:00",
        "Voltage": "230.12",
        "Frequency": "50.12",
        "Power": "23"
    },
    {
        "Timestamp": "2015-10-02 22:22:22",
        "Voltage": "231.12",
        "Frequency": "51.12",
        "Power": "23.4"
    }
]

I have tried looping through timestamps and then again through labels and values to create a new object array. However, with large amounts of data, this method becomes inefficient and crashes the browser. I would appreciate any suggestions on improving this process. Thank you.

Answer №1

When working with JSON data, it is important to remember that it is primarily used as a format for transporting and storing data. Instead of trying to directly manipulate the JSON itself, it is best to work with the JavaScript objects and arrays that it represents.

If you are able to maintain the original order of an array, you can use a method like the one below:

var outputArray = [];
var currentObj = null;
originalArray.forEach(function (element) {
  if (!currentObj || previousElement !== element.ID) {
    previousElement = element.ID;
    currentObj = {
      ID: element.ID;
    }
    outputArray.push(currentObj);
  }
  currentObj[element.Name] = element.Value;
});

This way, you can iterate through the data and construct the new array dynamically.

Answer №2

Upon reviewing the desired output, it appears that the timestamp trimming does not account for time and only focuses on date. If this was an oversight in the original question, feel free to make the necessary adjustments accordingly.

var b = a.reduce((acc, cur) => {
  var strippedTimestamp = cur.Timestamp.substring(1, 10) + " 00:00:00";
    var obj = acc.find(e => e.Timestamp == strippedTimestamp);
  if (!obj) {
    obj = { Timestamp: strippedTimestamp };
    acc.push(obj);
  }
  obj[cur.Label] = cur.Value;
  return acc;
}, []);

The resulting output will be as follows:

[
    {
        "Timestamp": "015-10-01 00:00:00",
        "Voltage": "230.12",
        "Frequency": "50.12",
        "Power": "23"
    },
    {
        "Timestamp": "015-10-02 00:00:00",
        "Voltage": "230.12",
        "Frequency": "50.12",
        "Power": "23"
    }
]

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

Is there a way to transfer a JSON map object from Flask and then utilize it as a JavaScript object?

python server code from flask import Flask, render_template, request import os import sys import json data_raw = [('0', '1', '0', '0'), ('0', '0', '1', '0'), ('1', ...

Performing calculations involving both select and checkbox input values, as well as handling negative numbers

Seeking assistance in creating a feature where users can select a billing term from a dropdown and then choose checkboxes to add to the total. While it works fine on JSFIDDLE, I encounter issues on my website - specifically when selecting all checkboxes, r ...

What is the best way to eliminate a CSS style from a div?

I have implemented jQuery Autosize to automatically adjust the height of textarea elements. It works perfectly when I focus on the textarea element. However, when I blur out of the textarea, I want to reset the height to its default value. I am unsure of ...

Using Vuex as a global event bus ensures that all subscribers will always receive notifications for

For a while now, I have relied on a global event bus in Vue - creating it as const bus = new Vue(). It works well, but managing subscriptions can get tedious at times. Imagine subscribing to an event in a component: mounted() { bus.$on('some.event ...

"The JSON response is a multidimensional array that returns an object containing another object

Looking to extract only the city names from my JSON data and insert them as option values into a form. However, my current script is returning all the information. What am I missing? Check out the code below: <script> $(function () { var shops ...

Varied elevations dependent on specific screen dimensions

There seems to be a minor issue with the height of the portfolio container divs at specific window widths. The problematic widths range from 1025 to 1041 and from 768 to 784. To visualize this, try resizing your browser window to these dimensions on the fo ...

Does the entire state get replaced every time a change is made if the state is immutable?

Is it necessary to replace the entire state if it is immutable? Otherwise, wouldn't mutating the state occur? Are top-level keys maintained as distinct immutable objects? Wouldn't changing anything necessitate replacing the entire state by defin ...

Exploring complex nested data structures

I've been tackling a component that manages labels and their child labels. The data structure and rendering process are sorted out, as shown in this example. However, I'm at a roadblock when it comes to manipulating the data effectively. Specif ...

Is there a way to capture real-time console output in an ExpressJS application while a script is running?

I'm facing a challenge in integrating the output of a bash script into an ExpressJS application to then send the data to a client. To address this, I have developed a simplified version of my actual script for testing purposes. My goal is to capture a ...

What is the method for determining the numerical worth of the px containers?

https://i.stack.imgur.com/0K2TD.png Total width of the bar is set to 500px, with the red box at a width of 150px, the yellow box at 200px, and the green box at 50px. CSS Styles: .box { float:left; width:150px; box-shadow:3px 3p ...

What is the best way to add a CSS style to any element that has the .btn:hover pseudo-class, except for those elements with the class '.dropdown-toggle'?

Is there a way to apply a style to all my .btn elements when hovering, except for those with the .dropdown-toggle class? I've tried a couple of methods but ran into some issues: attempt 1: .btn:not(.dropdown-toggle):hover { background-color: inher ...

Error encountered in parsing JSON: abrupt end of data (JavaScript)

I have been working on a few functions that are responsible for parsing JSON data, both external and internal, and displaying it on a local webpage using the localStorage feature. While I have successfully displayed the external JSON data, I am running int ...

Converting SWIG JSON objects into JSON objects on the client side

Currently, I am implementing Angularjs, although it seems like basic JavaScript can also do the trick. A summary of what has been achieved so far: console.log(JSON.parse({{{JSON.stringify(items)}}})); The variable items contains a JSON object. However, ...

When attempting to retrieve JSON-encoded data from an external PHP file using `json_decode`, no output is being generated

In the file _check_existing_transaction_partners.php echo '<pre>'; print_r($ajax_existing_company_error); echo '</pre>'; (using json_encode I have commented this out. Just as an example) The output is: Array ( [0] =& ...

What is the best way to locate all mesh faces that are being lit up by a SpotLight

I am working with a THREE.Mesh that consists of a THREE.BufferGeometry containing "position" and "normal" THREE.BufferAttributes. This mesh is being lit by a THREE.SpotLight (which is a cone-shaped light source). Is there a method to ...

How to show a sorted list in Python without using the list.sort method?

Exploring the realm of functions, I developed a sorting function for a list of numbers in Python 3.x: def insertion_sort(list): for index in range(1, len(list)): value = list[index] i = index -1 while i >= 0: if ...

Returning non-JSON formatted data in a .NET WCF JSON response

A current system is returning JSON data in a formatted form, however, a request has been made to return the data in a non-formatted JSON format. The current response is: {"GetBlendResult":[{"age":"0","dateofsomething":"23/09/1951 12:00:00 AM","firstn ...

React/Express: Error 413 encountered when posting due to payload size exceeding limit and Bodyparser failing to handle it

I've exhausted all options but this issue seems unsolvable. I have scoured every single suggested fix on stackoverflow and gone through 3 pages of Google search results. Methods I've attempted Inserted extended: true/false in bodyParser.json U ...

JavaScript - the global and local variable dilemma

REVISED2: I'm encountering an issue with converting images to canvas using Pixastic in HTML5. How can I 'return' this converted image back to a global variable? Any suggestions? <img id="mainIllustration" alt="main illustration" src="Img ...

Transforming a form containing recurring elements into JSON

Sorry if this topic has already been discussed, I wasn't able to locate any information I currently have an html form structured like so: <form> <div> First Name <input name="FirstName" type="text"> Age <input name="Age" t ...