What is the best way to flatten a nested array of objects with lodash?

I'm trying to convert a JSON object into a different format using JavaScript and lodash:

{
    "BidNumber": 2,
    "BidResult": 1,
    "BidAmount": "6756",
    "BidData": [
        {
            "name": "JonSnow",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "HarryPotter",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "MickyMouse",
            "Data": "Standard data for Micky Mouse"
        }
    ],
    "BidReference": "22e06e66-e711-bd14-7874a-002219649f24"
} 

My goal is to transform it into this structure:

{
    "bidNumber": 2,
    "bidResult": 1,
    "bidAmount": "6756",
    "bidData": {
        "jonSnow": "Standard data for Jon Snow",
        "harryPotter": "Standard data for Jon Snow",
        "mickyMouse": "Standard data for Micky Mouse"
    },
    "bidReference": "22e06e66-e711-bd14-7874a-002219649f24"
}

I'm having trouble finding the right lodash method to achieve this, especially with the camelCase conversion.

Answer №1

Implementing this in JavaScript is quite simple...

data.BidData = Object.assign({}, ...data.BidData.map(el => { 
  return { [(el.name ? el.name : el.LineNum)]: el.Data } 
}));

No need to rely on loadash unless you specifically require _.extend

var data = {
    "BidNumber": 2,
    "BidResult": 1,
    "BidAmount": "6756",
    "BidData": [
        {
            "name": "JonSnow",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "HarryPotter",
            "Data": "Standard data for Jon Snow"
        },
        {
            "LineNum": "MickyMouse",
            "Data": "Standard data for Micky Mouse"
        }
    ],
    "BidReference": "22e06e66-e711-bd14-7874a-002219649f24"
};

data.BidData = Object.assign({}, ...data.BidData.map(el => { 
  return { [jslcfirst(el.name ? el.name : el.LineNum)]: el.Data } 
}));


console.log(data);

function jslcfirst(string) 
{
    return string.charAt(0).toLowerCase() + string.slice(1);
}

Answer №2

Utilizing Lodash library:

obj.WidgetInfo = _.reduce(obj.WidgetInfo, function(flatObject, item) {
    flatObject[_.camelCase(item.name || item.LineNum)] = item.Data;
    return flatObject;
},{});

However, it is important to note that you can achieve the same result without the need for lodash (underscore) by using plain JavaScript

function convertToCamelCase(string) {
    return string.charAt(0).toLowerCase() + string.slice(1);
}

obj.WidgetInfo = obj.WidgetInfo.reduce(function(flatObject, item) {
    flatObject[convertToCamelCase(item.name || item.LineNum)] = item.Data;
    return flatObject;
},{})

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 iterate through index results using PHP?

I have a PHP code that retrieves a playlist from YouTube's API and displays the videos. The issue is that only 25 videos are shown per request. How can I add a "load more" link to my PHP script so that it requests another 25 videos? It can either relo ...

The cdkDropList in Angular's drag and drop feature does not support the application of element styles

Just wanted to share my experience in case it helps someone else out there! I've been working on an Angular project where I needed to create a Trello-like application. To enable dragging elements from one list to another, I installed the Angular cdk ...

What is the best way to cause an error to occur upon launching an ExpressJS server?

Below is a brief code snippet I've provided: ... const url = typeof process.env.url === 'string' ? process.env.url : {do not start a server} ... server.start(options, ({ port }) => console.log(`Server is running on http://localhost:${po ...

Configuration for secondary dependencies in Tailwind

As per the guidelines outlined in the official documentation, it is recommended to configure Tailwind to scan reusable components for class names when using them across multiple projects: If you’ve created your own set of components styled with Tailwin ...

The intersection of JSON and Java servlet technologies

I have created an HTML login page where users input a number. If the number matches a database entry, the user is redirected to a specific site. If the number is not found in the database, an error message is displayed. Currently, I am utilizing a Java s ...

Initiate an ajax request only when there are pre-existing ajax requests in the queue

Setting up the Form I've created a form that utilizes checkboxes to determine a selected number on a page: https://i.sstatic.net/BNQB0.png When a checkbox is selected, it triggers a call to a controller that saves the selection and returns the upda ...

Tips for synchronizing text field and formula field content on MathQuill 0.10

I am currently working on creating a WYSIWYGish input element for my formula, along with a LaTeX input element. <span id="editable-math" class="mathquill-editable"></span> The goal is to make these two elements work synchronously. Here's ...

How can we ensure that the previous selection is cleared in jQgrid only if the checkbox is not clicked

I've set up a grid with the option for multiselect: true so that I can delete multiple rows at once. When the onSelectRow event is triggered, data related to the ID is loaded and shown to the user. Everything seems to be working fine in this example ...

Receiving an initialized object rather than the expected response from the service

When using the POST method to send an object as a parameter to a service method, I am encountering an issue where Spring is returning an initialized object (with zeros and nulls) instead of the expected result. Interestingly, everything works perfectly fi ...

Error Loading JQuery: The function $() is not recognized in the Shopify platform

I seem to be overlooking something obvious. I am using Shopify and have included jQuery in the head section of the theme.liquid file: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> This script is placed rig ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

What is the process of connecting a Yarn module to a Docker container in another repository?

I'm currently facing a challenge in linking a module to a Docker container from another repository. To provide some background, I have a container hosting a React application named launch-control-admin. This project relies on a yarn module called @com ...

I'm looking to add CSS transitions, like fade-ins, to a list of items in React in a way that the animations occur one after the other upon rendering. How can this be achieved?

I've scoured the depths of Stack Overflow and combed through countless pages on the internet in search of an answer to my query, but alas, I have not found a solution. So, my apologies if this question is a duplicate. Here's my conundrum: https ...

Alexa Account Linking - Error: Account linking credentials are not valid

I've been working on setting up an Alexa skill with account linking. After obtaining the Linking Authorization Code and exchanging it for an Access Token, I attempted to input all the necessary parameters: code, access token, and skill ID into the Ale ...

Trouble with Json syntax in the body using the Ruby Typhoeus gem?

Here is a snippet of code that I have been working with: require 'Typhoeus' url = Typhoeus::Request.new("https://fluidsurveys.com/api/v2/webhooks/subscribe/", userpwd: "username_test:password_test", method: :post, body ...

Having issues with 'direction' in React withStyles causing errors

I am experiencing an issue with my React website where I am using the withStyles feature to apply styles to a material-ui Grid element. Specifically, when attempting to use direction: "column" in the style, I encounter the error message provided below. Th ...

The callback function for the XMLHttpRequest object is not triggered when making a cross-domain request using jQuery/Ajax

Looking for some help with this code snippet I have: $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentCo ...

Attempting to dynamically link my "ng-true-value" in AngularJS

Working with values retrieved from a database, my goal is to include a checkbox, load the description, and provide 2 text boxes – one editable and the other read-only. Both text boxes initially display values from the database. When the checkbox is chec ...

Checking if an array exists after parsing JSON using jQuery

I am working on a solution to automatically submit form fields after triggering the onchange event. After making some changes, the JSON response I receive appears in this format: { "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error" } ] } ...

Is it possible to integrate a JavaScript library into the Vue prototype?

I've recently integrated ProgressBar.js library into my app, which is built using vue and laravel with laravel mix. After installing ProgressBar.js via npm install, I am unsure how to incorporate it into my .vue files. I'm considering adding it t ...