using lodash to convert objects into arrays while maintaining parent-child relationships

Is there a way to achieve this transformation in lodash or any other JavaScript/TypeScript method?

var obj = {
    a: [ {id:1},{id:2},{id:3}]
    b: [ {id:4},{id:5},{id:6}]
    c: [ {id:7},{id:8},{id:9}]
}
// Need to transform into 
var arr = [
{title:a, items:[{id:1},{id:2},{id:3}]},
{title:b, items: [ {id:4},{id:5},{id:6}]},
{title:c, items: [ id:7},{id:8},{id:9}]}
]

Answer №1

If you want to achieve this, you can make use of the Object.keys method:

var myObj = {
    x: [ {id:10},{id:11},{id:12}],
    y: [ {id:13},{id:14},{id:15}],
    z: [ {id:16},{id:17},{id:18}]
}

var output = Object.keys(myObj).map(function(keyVal) {
  return { label: keyVal, data: myObj[keyVal] }
})

console.log(output);

Answer №2

If you want a concise and easily readable solution, you can utilize lodash and ES6 in just one line of code:

_.map(obj, (items, title) => ({ title, items }));

There's no need to rely on Object.keys() thanks to the versatility of map() when working with objects. By defining the callback function to accept the object key and its corresponding value as parameters, you can streamline your syntax using object literal shorthand notation, as demonstrated here with items and title.

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

Challenges with showcasing the maximum and minimum values within a two-dimensional array

Hi there! I'm currently working on populating an array with random values ranging from 0 to 10000. Once these values are displayed on the screen along with their locations, I need to determine the max, min, and average values in addition to their resp ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...

Utilize a React function to incorporate an external link

Looking to create a link to Twitter using the href attribute but encountering errors with the atag. Is there an alternative method I could use? In essence, I want to have a picture on my homepage that, when clicked, redirects the user to Twitter. I' ...

Vuetify autocomplete with server-side functionality

I am looking to implement infinite pagination on the Vuetify autocomplete feature. My goal is to trigger the loading of a new page of items from the backend when I scroll to the end of the menu. Initially, I attempted using the v-intersect directive as fo ...

AngularJS JQ Widgets Chart Display Issue

Trying to incorporate a chart using JQ widget, the code snippet below shows my controller code. When making an ajax call to retrieve data from the server, the response is received but the chart displays the previous data of that variable as undefined. Hard ...

Is it possible to access your app directly from the browser without requiring any user prompts?

After successfully setting up my app for both android and ios with the necessary app link and universal link, I am now focusing on redirecting users from a specific website to my app. The mobile aspect is all set, but I need to work on the browser/server s ...

ng-repeat table grouping by date

How can I utilize *ngFor to generate an HTML table grouped by date in columns? Here is an example of a JSON List: [{ "id": "700", "FamilyDesc": "MERCEDES", "model": "Mercedes-BenzClasse A", " ...

What is the process for choosing an element, wrapping it in a <div>, and appending a class to it using only JavaScript?

When constructing a responsive website, all CMS entries are in markdown. It's not feasible to manually code the div into each new entry, so dynamic class addition is necessary. The task at hand involves selecting an <img> within a post and wrap ...

Improving React efficiency: What techniques can be used to prevent the entire component from re-rendering every time a prop changes?

Issue at Hand I created a custom component named PageLayoutSideBar.tsx that accepts two props: sideBar and content. This component is designed to make it easy to display the sideBar and page content with the appropriate styling and sidebar width. My conce ...

Tips for effectively narrowing the `undefined` type

Why am I getting this error message? const func = (a: unknown) => { if (a && typeof a === 'object' && 'b' in a) { a.b; } }; The error message I'm receiving is: Property 'b' does not exist on ty ...

Incorrectly loading static images in React SSR

I am currently working on a React SSR app and my folder structure looks like this: https://i.sstatic.net/RA2H2.png My static express middleware successfully handles static files and images in the tag on the client side: https://i.sstatic.net/Zhzf2.png ...

Choose key and value pairs in AngularJS

Currently, I am retrieving JSON values from an HTTP service for each ID and attempting to create a dropdown with a list of names and IDs as keys to store. Below is the HTML code snippet: <select> <option ng-repeat="(key, value) in data" value="{{ ...

Reflector has no definition in three.js - a software mystery

After implementing the code snippet from the webgl_mirror example, I attempted to add a reflector surface to my scene. It seems that the following code snippet is all that's needed to introduce a reflective object to the scene: var geometry = new TH ...

JSON payload with an array that includes nested JSON objects

I am struggling with JSON objects and need to create a JSN structure similar to the following: { name: 'root', children: [ name: 'son1', children: [....] ] } Could someone please guide me on how to construct it using Java ...

Animate the background image with a float effect using jQuery's timeout feature to create an up

I'm having an issue with a set of elements that have background images applied to them. Specifically, I want the planets in the images (all except the first one) to move slightly up and then back down to create a floating effect. In my jQuery code, I ...

Several conditional statements in JSX

In my JSX Return() code, I am encountering an "If" issue when one of my conditions has 2 different 'onClick' events. There are 2 'a' tags, where one will display button 'X' if a statement is true and the other will display but ...

Manipulate object position using Aframe and three.js

I'm working on developing a game using A-frame. I'm trying to add a shooting effect by incorporating a gun model that follows the user's cursor. I've coded a click event so that an object moves in front of the gun and follows the direct ...

Reveal content as you scroll

I'm having trouble with the code snippet below. My goal is to utilize .cbp-fbscroller in my CSS to show a new side navigation menu on my HTML page only when scrolling down to 900px. However, as someone who is new to JavaScript, I am struggling to make ...

Issue with window.getSelection() function in Mozilla Firefox

I have implemented code to retrieve the window.getSelection() and assign it to a variable in order to store the current focusNode and offset when the contenteditable div onBlur event is triggered. This functionality works as expected in the Chrome browse ...

Ensure consistency in CSS3 background color transitions

There are multiple elements on the webpage with background transitions that change from one color to another: @-moz-keyframes backgroundTransition /* Firefox */ { 0% {background-color:#ff7b7b;} 33% {background-color:#7fceff;} 66% {backgr ...