Tips for re-formatting JSON data using Lodash / JavaScript

Can anyone help me with reformatting the JSON data below?

[
  {
    "name": "Hello",
    "value": 1
  },
  {
    "name": "Hello",
    "value": 11
  },
  {
    "name": "Bye",
    "value": 2
  },
  {
    "name": "Bye",
    "value": 22
  }
]

I want to transform it into the following format:

[
  {
     "Hello": 1,
     "Bye": 2
  },
  {
     "Hello": 11,
     "Bye": 22
  },
]

I'm struggling with this task and unsure about the approach. Can this be achieved using Lodash or pure JavaScript?

Answer №1

Before coming across Lodash, the following pure JS solution can be used with two nested loops:

function customConvert(longList)
{
    var shortList = [];
    for(var i = 0; i < longList.length; i++)
    {
        var key = longList[i].title;
        var value = longList[i].data;
        var obj = null;
        for(var j = 0; j < shortList.length; j++)
        {
            if(shortList[j][key] === undefined)
            {
                obj = shortList[j];
                break;
            }
        }
        if(obj === null)
        {
            obj = {};
            shortList.push(obj);
        }
        obj[key] = value;
    }
    return shortList;
}

In essence, this translates to:

Loop through all elements in longList.
For each element, loop through all elements in shortList to find the first element where the current title is not defined.
Create a new object if no match is found.
Assign the current data to the obj with title as the key.

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: Unable to encode data into JSON format encountered while using Firebase serverless functions

I am currently working on deploying an API for my application. However, when using the following code snippet, I encountered an unhandled error stating "Error: Data cannot be encoded in JSON." const functions = require("firebase-functions"); const axios = ...

Disabling the submit button after submitting the form results in the page failing to load

I am encountering an issue with my HTML form that submits to another page via POST. After the form validates, I attempt to disable or hide the submit button to prevent double submission and inform the user that the next page may take some time to load. He ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

Retrieve particular attributes from an array of objects

I have an array of JavaScript objects structured as follows: let users = [{ "id": 9, "name": "Sulaymon", "family": "Yahyaei", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="deadabb2bfa7b3b1b0b6b99eb ...

Issue with rendering Angular templates

Having just embarked on my AngularJS journey, I'm currently facing an issue with this specific code snippet. The following is an excerpt from my JavaScript file named cribsController.js: angular .module('ngCribs') .controller('cribsCo ...

I am having trouble viewing the JSON data on my activity's RecyclerView, which has been stored on a web server and accessed via a URL

When I try to run my activity, I am encountering an issue where I cannot see any JSON data from the webserver in my RecyclerView. All I see is a progress bar followed by an empty activity. I have already verified my adapter, I have set the adapter in the ...

Open the iframe link in the main window

As a newcomer to this platform, I am trying to figure out how to make a link open in the parent page when clicking a button within an iframe. Currently, my code opens the link in a new window. <html> <body> <form> <div class ...

Joi mistakenly demanding certain fields that should not be mandatory

I've encountered an issue with posts validation using @hapi/joi 17.1.1. In my schema, I have two fields: textfield and picture. Although both fields are not required, the validation is still indicating that the picture field is mandatory. posts valid ...

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

Leveraging npm packages in Meteor's Angular 1.3 framework

Although it may sound like a silly question, I am still confused. It has been said that Meteor has native support for npm modules in version 1.3. I am currently using Meteor with Angular integration. From the tutorial, it appears that using npm modules sh ...

Issue with retrieving JSON data in chart object: Error reading property 'length' of undefined in Angular/ng2-charts

     I have successfully retrieved JSON data in the following format:    [2193,3635,8417,0] The data is coming from localhost:8080. I aim to utilize this dataset for displaying a pie chart. Below is the code snippet from one.html: <div> ...

Guide on merging two JArrays using JSON.NET

Is there a way to properly concatenate two JArrays that were obtained through JArray.Parse? It is critical that the order of the arrays is maintained, with the first array appearing first followed by the elements from the second array. ...

When utilizing jQuery, I implemented this code but it does not display anything. I am unsure of the error within the code

When using jQuery, I implemented the following code snippet but it doesn't display anything. What could be causing this issue? // $.ajax({ // URL:"https://dog.ceo/api/breeds/image/random", // method:"GET", // ...

Error: Scheme is not a valid function call

Currently, I am attempting to implement user registration functionality in a Node.js application using MongoDB. However, I encountered this error: var UtenteSchema = Scheme({ TypeError: Scheme is not a function Below is my model utente.js: cons ...

Enhance User Experience with the Tooltip Feature and Customized

Here is the jQuery code I am using to style my tooltips: $(function() { // select all input fields within #tooltips and attach tooltips to them $("#tooltips :input").tooltip({ // place tooltip on the right edge position: "cen ...

Tips for removing a row from a table

I've been working on a responsive data table where each time I click an add button at the end of a row, a new row is added with the add button turning into a delete button. Below is the code I've implemented: The Table: <table id="invoice_ta ...

Choose a shade from Three.js' color selector

Currently working on a project using A-FRAME, I am in the process of creating a menu for hololens. However, I am facing some challenges with a color picker. I have developed a color picker (link: Color picker) and my goal is to select a color and have it d ...

Trouble with downloading a file from an HTML hyperlink

When I attempt to download a file from my file folder using the absolute path <a href='N:\myName\test.xlsx'>download</a>, the file opens directly instead of downloading. However, if I use the relative path <a href=&apos ...

The code is malfunctioning on this site (yet functions perfectly on a different website)

So I have a question that may seem silly, but it's worth asking. I'm attempting to create a sticky div element that stays in place when you scroll past a certain point on the page. This is the script I have: <script type="text/javascript"> ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...