Access the value of a field inside nested objects (Parent-child) by using underscore.js

const paths = [
 {
  path: 'RS',
  hasChild :true
 },
    {
     path: 'MO',
     hasChild: true
    },
       {
        path: 'EL',
        hasChild: true   
       },
          {
            path: 'CL',
            hasChild: false
          },
       {
        path: 'EL1',
        hasChild: true   
       },
          {
            path: 'CL1',
            hasChild: false
          },
{
  path: 'RS2',
  hasChild :true
 },
    {
    path: 'MO2',
    hasChild: true
    },
      {
       path: 'EL2',
       hasChild: true   
       },
          {
            path: 'CL2',
            hasChild: false
          },
          {
            path: 'CL3',
            hasChild: false
          },
];

Can underscore.js be used to create a complete path from the 'paths' object? For example:
RS\MO\EL\CL
RS\MO\EL1\CL1
RS2\MO2\EL2\CL2
RS2\MO2\CL3\CL3
In any of the above levels, children can appear more than once. Can underscore.js perform deep watching of nested arrays of objects?

I apologize for the poor formatting of the nested array of objects above.

Answer №1

function extractPaths (nodes)  {
  var buffer = [], pathsList = [];
  nodes.forEach(function (node) {
    if (node.hasChild) {
      buffer.push(node.path);
    }
    else {
      var tempBuffer = buffer.slice();
      tempBuffer.push(node.path);
      pathsList.push(tempBuffer.join('/'));
      buffer.splice(buffer.length - 1, 1);
    }
    if (/^RS/.test(node.path)) {
      buffer.splice(1, buffer.length);
    }
  });
  return pathsList;
}

New Paths: ['RS/MO/EL/CL', 'RS/MO/EL1/CL1', 'RS/MO2/EL2/CL2', 'RS/MO2/CL3']

Answer №2

Utilize _.each method for this task

var path = ""

_.each(levels, function(object){

 path = path + object.path + "/"
})
console.log(path)

Output: "RS/MO/EL/CL/EL1/CL1/RS2/MO2/EL2/CL2/CL3/"

Edit:

I believe your JSON should be structured like below:

var levels = [
        {
        "path": "RS",
        "hasChild": true,
        "children": {
            "path": "MO",
            "hasChild": true,
            "child1": [
                {
                    "path": "EL",
                    "hasChild": true
                },
                {
                    "path": "CL",
                    "hasChild": false
                }
            ],
            "child2": [
                {
                    "path": "EL1",
                    "hasChild": true
                },
                {
                    "path": "CL1",
                    "hasChild": false
                }
            ]
        },
        "isParent": true
    },
    {
        "path": "RS2",
        "hasChild": true,
        "children": {
            "path": "MO2",
            "hasChild": true,
            "child1": [
                {
                    "path": "EL2",
                    "hasChild": true
                },
                {
                    "path": "CL2",
                    "hasChild": false
                }
            ],
            "child2": [
                {
                    "path": "CL3",
                    "hasChild": true
                },
                {
                    "path": "CL3",
                    "hasChild": false
                }
            ]
        },
        "isParent": true
    }
]

To validate if the JSON is correct or incorrect, visit JSONLINT

Omit variable name during validation

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

Each time I attempt to read a single document, Next.js and Firebase consistently encounter serialization errors

Currently, I am in the process of developing a blog website, and most of it is completed except for the functionality of being able to click on a post stub to read the full post. Whenever I try to navigate to the post page, I encounter the following error: ...

Ways to pass Angular variables to JavaScript while utilizing the $scope() function

This is my process for receiving input: extracting data from an sql table, passing it through php slim, integrating it into angularjs, and displaying it on a website. I am looking to retrieve a variable in javascript that has been passed from php slim to ...

Guide on calculating the total sum of each element in a column within a multidimensional array

Hello, I am currently working on understanding multiple repetition and arrays. I need some assistance in calculating the sum of each value in a column of a multidimensional array. Here is the input I have: 2 -> number of test cases 3 -> size of arr ...

Admin-on-rest sidebar navigation menu

Hello everyone! I am new to ReactJS and admin-on-rest. I am currently studying from this documentation and I am interested in creating a navigation submenu similar to the one shown here. I have tried searching on Google but haven't found what I need. ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

Function that recursively checks for the existence of an ID within a nested object structure

I need assistance in developing a function that can determine whether the link ID of an object or any of its children match a specific ID. For instance, if the link ID for Product paths is 51125095, the function should return true when this ID is passed in ...

Differences between using Array.from and a for loop to iterate through an array-like object

When traversing an array-like object, which method is more efficient for performance: using Array.from( ).forEach() or a traditional for loop? An example of an array-like object would be: let elements = document.querySelector('#someid').children ...

Adding an element to an array in Angular 2 when an object is clicked

Whenever a row of objects is clicked, I want it to be added to the selectedProducts array. Within my TypeScript file: selectedProducts: Product[] = []; select(product) { this.selectedProducts.push(product); console.log(this.selectedProducts); ...

What is the best method for retrieving the character's ID from within an object?

Exploring my collection of movies, I discovered that each movie contains an array of characters. My goal is to display specific information about each character (such as their name and age) when clicked on, requiring me to obtain the id of each character. ...

Having trouble retrieving Bengali-language data from the server using jQuery AJAX

I am facing an issue where I am unable to fetch data in Bengali language from the server using ajax. Strangely, the data retrieved from the server is getting replaced by some unknown characters. However, if I directly retrieve the data without using ajax, ...

Exploring discrepancies in jQuery AJAX responses between Chrome and Firefox

As someone who is not a front-end developer, I find myself working on a casual project that involves using AJAX to retrieve a piece of JSON data. $('#btn1').click(function() { $.ajax({ url: 'http://mywebsite.com/persons/mike&apo ...

Tips for grouping radio buttons that span multiple rows within an ag-grid

I am currently working on a grid layout that consists of multiple rows, with each row containing a radio button as illustrated in the snapshot below: https://i.sstatic.net/O8i0r.png Here is the code snippet for the column definition of the radio button: ...

How to automatically scroll to the bottom using jquery/css

I've recently developed a chatroom using li elements, but I'm encountering an issue where the chat doesn't stick to the bottom once it reaches a certain number of messages. I suspect it has something to do with the height settings, but I can ...

I am unable to submit the form to the server

I'm experiencing an issue with my login form. I've tried submitting it using jQuery, but it's not working as expected. I've searched online for solutions, but they all seem too complex. Here is the code I'm working with: <form ...

Error alert: Controllers and services within the same module are experiencing injection issues

I'm in the process of creating an angular module that contains controllers and a service all within the same module. The issue I'm facing is an unknown provider error Error: $injector:unpr. I have made sure not to redefine the module multiple tim ...

Clicking on "Ng-Click" will add a fresh row to the table using Angular

Is there a way to insert a new row into a table using ng-click? I currently have the following setup with the data stored in an array. Here is how my array looks. $scope.workflows = [{ Id: 1, Name: "Workflow Page 1", ...

Using ReactJS to send formData to an Express API and retrieving a JSON response

Attempting to have the ReactJS frontend send a username and password from a form to my express API via a proxy, with the intention of having the API return a JSON file containing a user id. While the proxy connection is working as expected, the issue arise ...

Learn how to extract data from the "this" object in JavaScript

Can anyone help me with retrieving the numbers generated by this code snippet? $("#100wattaren") .countdown("2018/01/01", function(event) { $(this).text( event.strftime('%D days %H hours %M minutes %S seconds') ); }); When I con ...

The Android Quiz app that deems correct answers as incorrect

I've been working on a quiz app where I manually input questions and answers into an array, and use this data to populate radio buttons and text views. However, I've encountered an issue where the correct answer becomes incorrect as I progress th ...

Only a singular operation is carried out

Contained within my .js file are two functions: function download510(form) { if (form.pass.value=="tokheim") { location="../pdf/quantium-510.pdf" } else { alert("Invalid Password") } }; function download410(for ...