Utilize lodash to condense an array of objects into a compact

I have an array of objects, similar to the first JSON shown below.

My goal is to group and zip this array based on the attribute name. If the name matches another object, I want to combine them and set all attributes and values into a 'fields' array.

[ 
   { 
      "name":"D1D1",
      "attritube":"HOST_NAME",
      "value_inv":"TEST1",
      "value_prod":"TESTA1"
   },
   { 
      "name":"D1D1",
      "attritube":"HOST_NAME",
      "value_inv":"TEST2",
      "value_prod":"TESTB1"
   },
   { 
      "name":"D2D2",
      "attritube":"COMMENTS",
      "value_inv":"TEST1",
      "value_prod":"TESTA1"
   }
]




[ 
   { 
      "name":"D1D1",
      "fields":[ 
         { 
            "attritube":"HOST_NAME",
            "value_inv":"TEST1",
            "value_prod":"TESTA1"
         },
         { 
            "attritube":"HOST_NAME",
            "value_inv":"TEST2",
            "value_prod":"TESTB1"
         }
      ]
   },
   { 
      "name":"D2D2",
      "fields":[ 
         { 
            "attritube":"COMMENTS",
            "value_inv":"TEST1",
            "value_prod":"TESTA1"
         }
      ]
   }
]

Answer №1

While this solution may not be the most efficient for handling large datasets, it gets the job done and delivers the expected output.

const data = [ 
   { 
      "name":"D1D1",
      "attritube":"HOST_NAME",
      "value_inv":"TEST1",
      "value_prod":"TESTA1"
   },
   { 
      "name":"D1D1",
      "attritube":"HOST_NAME",
      "value_inv":"TEST2",
      "value_prod":"TESTB1"
   },
   { 
      "name":"D2D2",
      "attritube":"COMMENTS",
      "value_inv":"TEST1",
      "value_prod":"TESTA1"
   }
];

const newData = _.chain(data)
  .groupBy('name')
  .toPairs()
  .map((item) => ({
    name: item[0],
    fields: _.map(item[1], (value) => _.omit(value, ['name']))
  }))
  .value();
  
console.log(newData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

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

Attempting to access a shared php/javascript library using mod_rewrite

Let's dive into a fresh perspective on a question I previously raised: I've crafted a mod_rewrite snippet that checks for the existence of JavaScript, CSS, and PHP files on the subdomain they are called from (e.g., subdomain.example.com). If the ...

Complete Search with the press of Enter on the Auto Textbox

I have implemented an Ajax auto complete extender on a TextBox control. As the user begins typing, suggestive options are displayed below the input field based on data retrieved from a webservice call. When OnClientItemSelected="GetCode" is triggered, the ...

Unlimited scrolling gallery with multiple rows

I am looking for a way to create a multi-row infinite loop scrolling gallery using html, css, and javascript. Can anyone help me with this? ...

How to Send a JavaScript Array to a JSP Endpoint

I'm in the process of creating a web application that interacts with another website through a JS API. I would like to incorporate an array of JSON objects obtained from this API into my Java Application. Is there any way to submit this array, perhap ...

Fill the drop-down list using a loop

How can I dynamically update the options in a select box based on user selection? This is what I have tried so far, but it's not working: $('select#mnt').change(function(){ var month = $(this).val(); var days = new Date(year, mo ...

Enable draggable feature using JQuery - revert div elements to original parent upon click

As a beginner in JQuery, I have gone through multiple tutorials online and sought answers on various forums, but I'm stuck on a specific issue and would greatly appreciate any assistance. My goal is to create a function where there are draggable and ...

Testing Jasmine asynchronously with promise functionality

During my Jasmine testing with angular promises, a question arose regarding timing. I came across a post at Unit-test promise-based code in Angular, but I still need some clarification on how it all functions. The concern is that since the then method is ...

Developing a constructor method that is conscious of data types

In my current scenario, I am dealing with a set of types: X, Y, and Z, all of which extend the same common interface J. My goal is to define a method that looks like this: class MyClass { private someNumber = 1; private someProperty; addEleme ...

Tips for successfully transferring an image through an XMLHttpRequest

I found this helpful resource at: I decided to test out the second block of code. When I made changes in the handleForm function, it looked like this: function handleForm(e) { e.preventDefault(); var data = new FormData(); f ...

What is the best way to implement ngModel globally in my application?

As a newcomer to Angular 5, I am struggling to display values from the Add screen to the View screen using ngModel. My aim is to have the values added in the Add screen appear in the View screen's table. // In my App.module.ts file import { Browser ...

Executing a function within another function (triggering the logout action by clicking the logout link) in ReactJS

Is there a way to access a method outside the render function and call it inside another function in order to log out the user with a simple click? I encountered the following error: Cannot read property 'AuthLogout' of undefined Let me shar ...

modify the inherent CSS property

I am working with a component that I have inherited, including its CSS style, and I need to modify one of its properties. Current CSS: .captcha-main-image { width: 100%; height: auto; } <img class ="captcha-main-image" id="captchaImage" src= ...

Using three.js and gsap to create interactive mousemove effects

I've been attempting to create a mousemove event that scales the mesh when the mouse hovers over it, and returns it to its original size when the mouse is no longer hovering. I've looked at examples that use tween.js instead of gsap, but my synta ...

Angular 5 - Empty array containing objects has a length of zero

In my app.component.ts file, I have an array initialized to load objects in the onInit event: ngOnInit() { this.pages = []; } Within the ngOnInit event, I also have a setInterval method that evaluates an expression every few milliseconds: setInterval(() ...

Showcasing a single object in an IONIC/Angular application using the ngIF directive

I am in need of assistance as I have encountered an issue. Essentially, I am fetching an object from an external API (Strapi) using the GET method, but when attempting to display it on Views with ngIF, it fails to show up. https://i.sstatic.net/nFyOE.png ...

Integrating external information with components

Currently in my React application, I am fetching a list of stores by directly calling the API through the URL. const getStore = async () => { try { const response = axios.get( 'http://localhost:3001/appointment-setup/storeList& ...

Validating a TypeScript type against an enum

I have two categories, the first one being an enum: enum Vehicle { Car = 'car', Plane = 'plane', } The second category is a regular object that utilizes the enum as keys: type VehicleProperties = { [Vehicle.Car]: { amountOfWhe ...

Vue - Issue with reading properties of undefined while dropping a file

Trying to drag and drop an mp3 file into a dropbox on my website is proving challenging. Each time I test it, no matter the file I drop, the same error persists: Uncaught TypeError: Cannot read properties of undefined (reading 'files') Below is ...

One effective way to remove bold formatting from text that has been altered using execCommand

While I am utilizing document.execCommand to bold and underline text, what I really need is a button that can unbold the text and remove any underlining instead of just toggling them. Unfortunately, using execCommand("removeFormat") is causing some issue ...

Does the router navigate function instantly update the router URL?

I'm testing whether the navigate function will immediately alter the router URL upon execution. this.router.navigate(['/home/products']); if (this.router.url.includes('/home/products')) console.log('URL has been changed&apos ...