Use underscore.js to flatten an object structure into a key-value pair array of children

After analyzing the given data structure:

var data = [{
    name: "Some Name",
    id: 1,
    children: [
        { name: "prop1", value: 1 },
        { name: "prop2", value: 2 },
        { name: "prop3", value: 3 }
    ]
},
{
    name: "Some Other Name",
    id: 2,
    children: [
        { name: "prop1", value: 4 },
        { name: "prop2", value: 5 },
        { name: "prop3", value: 6 }
    ]
}];

...with a dynamic list in 'children', I successfully restructured this using nested _.each loops like below:

_.each(data, d => {
    _.each(d.children, c => {
        d[c.name] = c.value;
    })
});

This resulted in a new 2-dimensional data structure as shown:

[{
    name: "Some Name",
    id: 1,
    prop1: 1,
    prop2: 2,
    prop3: 3
},
{
    name: "Some Other Name",
    id: 2,
    prop1: 4,
    prop2: 5,
    prop3: 6
}];

Looking for a more efficient way to achieve this restructuring using undercore.js?

Try it out on JSFiddle: http://jsfiddle.net/3m3dsv47/

Answer №1

Here's another creative solution that I devised:

_.each(data, d => {
    _.extend(d, _.object(_.map(d.children, c => {
        return [c.name, c.value];
    })));
});

Check out the code on jsFiddle!

Answer №2

Utilizing UnderscoreJS, this solution differs from your approach by not altering the original data but instead creating a duplicate of it. While I wouldn't go as far as calling it "much neater", here is an alternative:

_.map(data, function(e){ 
    return _.defaults({name: e.name, id: e.id}, 
      _.reduce(e.children, function (acc, e) {
        acc[e.name] = e.value; return acc; 
      }, {})
    ); 
  });

When applied to your dataset, the outcome would be:

 [
   {"name":"Some Name","Prop1":1,"Prop2":2,"Prop3":3},
   {"name":"Some Other Name","Prop1":4,"Prop2":5,"Prop3":6}
 ]

An alternative approach would be to eliminate the _.reduce. Although it may appear more elegant, it is less efficient due to double iteration over all children (_.pluck) compared to the initial method.

_.map(data, function(e){
    return _.defaults({id: e.id, name: e.name}, 
      _.object(_.pluck(e.children, 'name'), _.pluck(e.children, 'value'))
    );
});

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

SQL stores Array Input as a static identifier 'Array'

Previously, I was able to save an object in the database. However, now I need to save each individual data in an array within a row. I attempted to use array_column to store a specific set of data in a column, but it ended up saving as the word 'Array ...

"Losing focus: The challenge of maintaining focus on dynamic input fields in Angular 2

I am currently designing a dynamic form where each Field contains a list of values, with each value represented as a string. export class Field { name: string; values: string[] = []; fieldType: string; constructor(fieldType: string) { this ...

Using JavaScript in Node, you can pass an object by throwing a new Error

How can I properly throw an error in my node application and access the properties of the error object? Here is my current code: throw new Error({ status: 400, error: 'Email already exists' }); However, when I do this, I get the following outpu ...

Generate a collection of LatLng coordinates to represent a worldwide grid

I'm in search of a quick and easy solution, like a simple library or similar tool, that would allow me to call a function like createGlobalGrid(1000) and automatically generate a list of points on a geospatial surface, ensuring that each point is no m ...

Counting the occurrence of a specific class within an element using jQuery

Within my table, each row is assigned one or more classes based on its region. This is the structure of my table: <table> <thead> <th>Title</th> <th>Name</th> </thead> <tbody> <tr class="emea ...

Checking JSON formatted actions in Rails 4: A guide to testing

I'm in the process of testing a Rails application where all my actions return data formatted in json. An example of this is within the UsersController # POST /users.json def create @user = User.new(user_params) respond_to do |format| ...

What is the method for retrieving this data using Javascript?

I received this JSON-encoded data: { "error": { "msg":"Concurrent verifications to the same number are not allowed", "code":10 } } and I tried to access the 'msg' value using JavaScript as follows: $("#buttonPhoneSubmit ...

Best practice for stopping routing in angular

I am currently working on an angular application that includes guest functionality. This feature allows me to create a guest account for all unauthorized users in the background. I need to pause routing until the guest account is created and then specify a ...

Combining Prisma results into a unified object

I am currently working on a project using nextjs 13 and prisma ORM with MongoDB. My task involves fetching roles along with their permissions to create an admin role matrix. Here is the schema for the Role model. model Role { id String @id @de ...

Calculating the mean value of the numbers provided in the input

I'm struggling with calculating the average of numbers entered through a prompt window. I want to display the numbers as I've done so far, but combining them to find the average is proving difficult. Here's the code I have: <html> &l ...

Exploring data segments in Knockoutjs using various models

I'm trying to figure out why Knockout.js won't allow me to access specific parts of the model data. Could it be because I am binding the model to the div that contains all the submodels (such as the Form in this example), or am I approaching this ...

The DELETE function in express.js with MySQL integration is encountering a problem where it is unable to

As I work on setting up my website, the backend utilizes express.js to send queries to a MySQL Database. However, when attempting to delete rows, no action seems to take place. function establishConnection() { return mysql.createConnection({ multipl ...

My React application is being loaded by Express regardless of the route I access. What could be causing this issue?

I'm struggling to access the json data located at /species because express always seems to load the react app regardless of the route I use. Can someone help me identify the issue? Here is an excerpt from my server.js file: const app = require(' ...

Developing an Angular template component integrated with Express JS backend

I'm encountering an issue while attempting to load a template file from one of my folders in Angular. I have my JS files statically called with Express, however, the template files are not loading. I have tried placing them in the views folder along w ...

Jquery Deferred failing to activate done or when functions

I'm currently working with 2 ajax calls that I'm connecting using $.when in order to execute certain tasks once they are completed. Below is the code snippet: function ajaxCall(url, targetDiv) { dfd = new $.Deferred(); $.ajax({ ...

Refresh a Particular Section of a Website Without Having to Reload the Entire Page

I have this PHP script that I'm using to read specific phrases from a text file and then display one of them randomly on a webpage. Currently, the only way to see a new random phrase is by refreshing the entire page. I'm wondering if there is a w ...

Exchange one HTML element with a different HTML element

I've been attempting to change an HTML tag using PHP or jQuery. The current default tag is: <li class="dropdown"> <a href="index.html" class="dropdown-toggle"> Home</a></li> My desired replacement for the above HTML tag is: ...

How to access an HTML element in TypeScript similar to the use of the dollar sign ($) in JavaScript

In my current web project, I have implemented a parallax effect using JavaScript. The code selects an element with the class ".parallax" and calls the method "parallax()". This is essential for the parallax effect to function properly. $('.parallax&a ...

Does React include a mechanism for event dispatching and listening?

Recently, I've been exploring the intricacies of the Laravel framework and have been fascinated by its event dispatching and listening system. In the past, I've dabbled with electron which shares similarities with Laravel's system, but in m ...

Transfer information to an ExpressJS server in order to display a fresh view

I'm struggling to figure out how to transfer data from the client side to an ExpressJS server in order to generate a view based on that information. When users choose different parameters on the client side, they update the 'data-preference&apos ...