Using lodash in JavaScript to flatten a nested object structure

I'm looking to flatten a hierarchical json structure. Here is an example of my json data:

{
  "id": "111",
  "name": "v5",
  "define": {
    "system": "abc",
    "concept": [{
      "code": "y7",
      "concept": [{
        "code": "AGG",
        "display": "Abcess"
      }, {
        "code": "ABS",
        "display": "Abcess"
      }]
    }, {
      "code": "y8",
      "concept": [{
        "code": "AGc",
        "display": "ccc"
      }, {
        "code": "hjj",
        "display": "uii"
      }]
    }]
  }
}

Is there a way using lodash to flatten this json and extract only the "code, display" pairs into an array?

If not, are there any other libraries that can achieve this? Thank you.

For example, the desired output would look like this:

[{
  "code": "AGG",
  "display": "Abcess"
}, {
  "code": "ABS",
  "display": "Abcess"
}, {
  "code": "AGc",
  "display": "ccc"
}, {
  "code": "hjj",
  "display": "uii"
}]

Answer №1

This code snippet utilizes the Array#forEach() method to provide a solution.

var data = { "id": "111", "name": "v5", "define": { "system": "abc", "concept": [{ "code": "y7", "concept": [{ "code": "AGG", "display": "Abcess" }, { "code": "ABS", "display": "Abcess" }] }, { "code": "y8", "concept": [{ "code": "AGc", "display": "ccc" }, { "code": "hjj", "display": "uii" }] }] } },
    flat = function (array) {
        var r = [];
        array.forEach(function (a) {
            a.concept.forEach(function (b) {
                r.push(b);
            });
        });
        return r;
    }(data.define.concept);

document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');

Answer №2

How can I use lodash to transform this JSON into an array of "code, display" pairs only?

Are you asking if we should combine all the children under the `concept` key?

Here is a suggested solution:

var obj = {
  "id": "111",
  "name": "v5",
  "define": {
    "system": "abc",
    "concept": [{
      "code": "y7",
      "concept": [{
        "code": "AGG",
        "display": "Abcess"
      }, {
        "code": "ABS",
        "display": "Abcess"
      }]
    }, {
      "code": "y8",
      "concept": [{
        "code": "AGc",
        "display": "ccc"
      }, {
        "code": "hjj",
        "display": "uii"
      }]
    }]
  }
}

var output = [];

obj.define.concept.forEach(function(o) {
  output = output.concat(o.concept)
});

document.write("<pre>" + JSON.stringify(output, 0, 4) + "</pre>");

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

What is the reason behind AngularJS throwing an error related to bad augmentation?

Whenever I try to update the src link in my Angular code from version 1.2.2 to 1.5.0, I encounter an error. The code works perfectly fine with 1.2.2, but switching to 1.5.0 throws an error. I want to upgrade it to 1.5.0, so what changes do I need to make ...

"Resolving the problem of converting JSON to a C# class with integer class name

Received a JSON response with the following structure: { "serp": { "1": { "href": "href1.com", "url": "url1.com" }, "2": { "href": "href2.com", "url": "url2.com" ...

How to Configure a NoSuchPropertyException in Symfony's Serializer

When converting json to objects, I want to trigger an exception if a property exists in the json but doesn't match the properties of the class I am deserializing to. In the file Symfony\Component\Serializer\Normalizer\ObjectNormal ...

Looping Logic in iOS Threads

Can someone please help me with the process of setting up a continuous loop on a thread? I just need some guidance in the right direction. Should I use GCD or NSOperation? I have a JSON file that is updated by a web job every 5 minutes. Is there a method ...

Have you considered retrieving POST parameters using Ajax POST in jQuery?

Below is the code snippet: $.ajax({ type: "POST", url: "http://localhost:3000/rcm/global_config/update", data: {k: 'sdfa', v: 'dsfas'}, success: function(data, textStatus, XMLHttpRequest){ alert("Data ...

The JSON server middleware is malfunctioning and not functioning as intended

Currently experimenting with node.js/Express/json-server In my effort to monitor (and potentially edit) the request URL being sent to my API json-server, I have implemented the following middleware in my app's server.js file: // Setting up API JSON- ...

Enhance the language with react-intl and MobX State Tree integration

Currently, I am integrating react-intl with Mobx state tree for the first time. Within my project, there are two buttons located in the header section - one for 'it' and the other for 'en'. Upon clicking these buttons, the selected lan ...

Creating a JSON file that contains a collection of discord.js statuses and then seamlessly integrating it into the primary JavaScript document

const userActivities = [ { name: "Morning Jog", type: ActivityType.Running }, { name: "Afternoon Nap", type: ActivityType.Sleeping }, { name: "Evening Game Night", type: ActivityType.Gaming }, { name: "Late Night Code ...

Serialization of Entity Framework entity to JSON with included related entities

I am facing a challenge with my User entity as it has numerous relations to other entities within the system. I am utilizing AngularJs and aim to serialize the User entity to JSON with only the included entities. Below is my select statement: var users = ...

Revamp the appearance of angular material inputs

I have been working on customizing the style of an Angular Material input. So far, I successfully altered the background-color with the following code: md-input-container { padding-bottom: 5px; background-color: #222; } I also changed the placeh ...

A guide on transitioning from using require imports to implementing ES6 imports with the concept of currying

Currently in the process of migrating a Node/Express server to TypeScript. I have been using currying to minimize import statements, but now want to switch to ES6 import syntax. How can I translate these imports to ES6? const app = require("express")(); ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

Guide on creating a Google function using Twilio to automatically send an SMS when there is a change in the Realtime database

I am currently working on my first Google Cloud Function and I have limited knowledge about it. My goal is to create a Google Cloud Function integrated with Twilio. Whenever the water level changes in my Realtime Database, I want to send an SMS to a specif ...

Node Express Caching: What are the best strategies for managing view access?

When using Express, you can take advantage of its built-in cache mechanism by setting up with app.enable('view cache'). However, the challenge lies in distinguishing between views that should be cached and views that should always be served fresh ...

Run a batch file in the active window

Is there a way to launch a batch file in the foreground from a nodejs app (specifically node-webkit), regardless of its location? Currently, I am able to run the batch file using the following code: require('child_process').spawn(pathToBat, [], ...

Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at: Reading data from a CSV file (such as employee names and shifts) Displaying this data on FullCalendar. How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Audi ...

Choosing the image that represents your website in Safari web previews

Every time I check iCloud.com on my Safari top sites, the thumbnail is always the same. I'm curious about how I can automate this for my own website. ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

What are the specific purposes of utilizing semantic versioning (semver) notation within the package.json file?

Could someone clarify the specific distinctions between the semver notations found in package.json file? I'd appreciate a detailed explanation. ...

Obtaining template attributes in CKEditor: A guide

I have been working with the template plugin in CKEditor to load predefined templates. Each template is defined as follows: templates: [ { title: "Quickclick 1", image: "template1.png", description: "Quickclick 1 template", html_et: "& ...