Shifting the contents of a JavaScript array

My dataset consists of values categorized by different sections as shown below:

var data = [
{'name': 'Test 1',
'values': {
'50':0,
'51':10,
'52':0,
'53':10,
'54':60,
'55':999
}},
{'name': 'Test 2',
'values': {
'50':33,
'51':3,
'52':333,
'53':3,
'54':3,
'55':3333
}},
{'name': 'Test 3',
'values': {
'50':55,
'51':66,
'52':77,
'53':88,
'54':99,
'55':100
}}];

To transform this into a new array with each value separated, I would expect the result to look like this:

var result = [
{'value':50, 'Test 1':0, 'Test 2':33, 'Test 3': 55},
{'value':51, 'Test 1':10, 'Test 2':3, 'Test 3': 66},
{'value':52, 'Test 1':0, 'Test 2':333, 'Test 3': 77},
{'value':53, 'Test 1':10, 'Test 2':3, 'Test 3': 88},
{'value':54, 'Test 1':60, 'Test 2':3, 'Test 3': 99},
{'value':55, 'Test 1':999, 'Test 2':3333, 'Test 3': 100}
]

How can I iterate through the existing data array to create this new format?

Answer №1

One approach is to create an object that collects keys with their corresponding values and then extract the result set from this object.

var data = [{ name: 'Test 1', values: { 50: 0, 51: 10, 52: 0, 53: 10, 54: 60, 55: 999 } }, { name: 'Test 2', values: { 50: 33, 51: 3, 52: 333, 53: 3, 54: 3, 55: 3333 } }, { name: 'Test 3', values: { 50: 55, 51: 66, 52: 77, 53: 88, 54: 99, 55: 100 } }]
    result = Object.values(data.reduce((r, { name, values }) => {
        Object.entries(values).forEach(([k, v]) => {
            r[k] = r[k] || { value: +k };
            r[k][name] = v;
        });
        return r;
    }, {}));

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

Answer №2

If you find yourself dealing with messy data, this method provides a reliable and fault-tolerant approach to handling it efficiently.

var data = [
{'name': 'Test 1',
'values': {
'50':0,
'51':10,
'52':0,
'53':10,
'54':60,
'55':999
}},
{'name': 'Test 2',
'values': {
'50':33,
'51':3,
'52':333,
'53':3,
'54':3,
'55':3333
}},
{'name': 'Test 3',
'values': {
'50':55,
'51':66,
'52':77,
'53':88,
'54':99,
'55':100
}}];

var piv_data = [];

for(var i = 0; i < data.length; i++)
{
    var name = data[i].name;
    for(var value in data[i].values)
    {
        var index = -1;
        for(var x=0; x < piv_data.length; x++)
        {
            if(piv_data[x].value == value)
            {
                index = x;
                break; 
            }
        }
        if(index == -1)
        {
            piv_data.push({ 'value': value })
            index = piv_data.length -1;
        }
        piv_data[index][name] = data[i].values[value]
    }
}

console.log(piv_data)

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

Looking to dynamically generate HTML tags using jQuery and JSON?

Looking for help with inserting HTML code into a div using jQuery. <div id="addme"></div> Here is some HTML with PHP: <div class="col-md-4 product secondproduct"> <div class="images1"> <a href="<?php echo base_u ...

The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR: Error: NS_ERROR_FAILURE: Source file: http://localhost/Example/scripts/index.js Line: 18 Similar issue observed on Internet Explorer 11: SCRIPT5022: InvalidStateError The script used for AJAX function call i ...

The mysterious plugin "transform-runtime" has been detected in the ".babelrc" file located in "UsersPhpstormProjectseasy-essay"

After downloading a GitHub repository, I came across a file named .babelrc.json with the following contents: { "presets": [ "es2015", "stage-0" ], "plugins": [ "transform-runtime", "add-module-exports", "transform-decorators-lega ...

Leveraging Angular's capability to import files directly from the assets

I recently installed a library via npm and made some modifications to one of the modules. python.js If I delete the node_modules folder and run npm install, I am concerned that I will lose my changes. Is there a way to preserve these modifications by mov ...

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...

Issue with connect() method in React-Redux resulting in a TypeError

Currently immersed in the Redux tutorial by Dan Abramov, specifically on chapter 27 - Generating containers with connect(), encountering a rather peculiar bug: To start off, I define these two functions: const mapStateToProps = (state) => { return ...

Pass various arrays from JavaScript interface to C# MVC method

How can I input items (selectedPublishersList, selectedTranslatorsList, selectedAuthorsList) in this action? I have tried to pass the data from the view to the action, but the received value is always null in the controller. C# [HttpPost] public async Ta ...

How does the next() function work within the context of express.js middleware?

I'm really struggling to understand the purpose of "next" in this Express.js example and why it's being used in this context. This is the file where all my routing logic is being handled. const express = require('express'); const co ...

Tips on adding up the values of fields in arrays in mongoose

const PostSchema = new mongoose.Schema({ title: { type: String, }, text: { type: String, required: true, } postedBy: { type: mongoose.Schema.ObjectId, ref: "User", } likes: [{ type: mongoose.Schema.ObjectId, ref: " ...

After implementing the msw-storybook-addon, I encountered an error stating "Unexpected character '#' in node_modules/../Emitter.js."

Seeking to utilize mock servers for my stories, I encountered an error while setting up the Storybook with msw-storybook-addon. After following the steps outlined in both this and this resources (which have different instructions for preview.js), running t ...

I am encountering a 302 error when attempting to sideload images on Imgur using the API

I've been experimenting with sideloading using imgur's API. $.get("http://api.imgur.com/2/upload.json?", { url: www.example.com/blah.jpg },function(response){ var url = response.upload.links.original; var thumb_url = response ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

Retrieve the key from the array if the specified value is found in PHP

How can I quickly check if a variable's value is present in an array and return the corresponding key? For instance: $myArray = [ "test" => 1, "test2" = 2, "test3" = 3]; $var = [1,6,7,8,9]; I want to achieve if($var is in $myArray) return (in t ...

Transforming a Nestjs string object into JSON data

I need to convert this to JSON format. I attempted to use JSON.parse(), but encountered an error. "{"status":"00","message":"OK","access_token":"2347682423567","customer":{"name":"John Doe","address":"Mr. John Doe 34 Tokai, leaflet. 7999.","util":"Demo Ut ...

"Troubleshooting: Issues with message passing between popup.html and content.js in Chrome Extension

I'm facing a challenge in creating an Extension that transfers data from popup.html to the tab dome. Unfortunately, I am having trouble with getting the sendMessage function to work and I can't figure out why. I'm using the following guideli ...

Retrieve all nested content files and organize them by their respective directories in Nuxt content

My blogposts are stored in a list called articles fetched from the content folder. async asyncData ({ $content }) { const articles = await $content('', { deep: true }) // .where({ cat: 'A' }) .only(['title', ...

"jQuery's .each() method is only iterating through the last element in

I am encountering an issue with this function not operating correctly... only the last Element shows the box. NOTES: <aside> is set to position: fixed; and I understand that this is not the "correct" use of <article> tags, but it helps me dist ...

Managing numerous API requests in React Native

As I work on implementing a search field, I've encountered a challenge. Whenever a user enters text in the search field, a timer resets to 300 ms before an API call is sent to fetch autocomplete results. After receiving these results, the app then wai ...

Retrieve database SQL information using JavaScript to display data

I'm struggling to push the value from a textbox to SQL and display it. Despite reading numerous topics, I still can't figure it out. My explanation skills are lacking, but hopefully you can understand what I'm trying to achieve, especially i ...

I wonder where this design is originating from

After exploring several of the suggested questions that appeared while typing, I was unable to find a solution to my issue. Currently, I am utilizing Uikit V2 and I have implemented a div with the Sticky component as shown below: <div class="uk-st ...