Phuong Le Phuong Le - 3 months ago 8
JSON Question

JavaScript: How can I transform objects array A to objects array B in the efficiency way?

I got object array A as this:

[
{
"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 want to transform to object array B as this:

[
{
"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 was looping to get the timestamp and re-loop again to get label and value to form new object array. It works but when the data become few hundred thousands object array then it's not efficiency and crash the browser. Would someone can think of a better way please. Thanks very much.

Answer

JSON is just a transport/storage format. It's generally not something you should attempt to manipulate directly. Best to manipulate the actual JavaScript objects/arrays.

If you can guarantee the original array sort order, try something like this:

var outputArray = [];
var currentObj = null;
originalArray.forEach(function (measurement) {
  if (!currentObj || currentTimestamp !== measurement.Timestamp) {
    currentTimestamp = measurement.Timestamp;
    currentObj = {
      Timestamp: measurement.Timestamp;
    }
    outputArray.push(currentObj);
  }
  currentObj[measurement.Label] = measurement.Value;
});

Then, you can just loop through and build the new array as you go.