Combine nodes that share a common key

Looking for a solution to merge Treernode keys that might be the same in order to eliminate duplicate folders.

ParentObj = [{
"data": {
    "resTitle": "-JANAF Thermochemical Tables - SRD 13"
},
"children": [{
    "data": {
        "filePath": "borides"
    },
    "children": [{
        "data": {
            "filePath": "titanium"
        },
        "children": [{
            "data": {
                "filePath": "srd13_B-102.json"
            },
            "children": []
        }]
    }]
}, {
    "data": {
        "filePath": "borides"
    },
    "children": [{
        "data": {
            "filePath": "titanium"
        },
        "children": [{
            "data": {
                "filePath": "srd13_B-103.json"
                },
                "children": []
            }]
        }]
}]
}]

The goal is to consolidate 'borides' so that 'titanium' and 'zirconium' are nested under 'borides'. 'Borides' will act as the parent for 'titanium' and 'zirconium'.

The desired structure would look like this:

borides -

  • titanium - B-102.json
  • zirconium - B103.json

Provided below is the code snippet currently being utilized:

 var arr = JSON.stringify(parentObj);
  var result = [];

  for (var i = 0; i < arr.length; i++) {
  console.log("inside i loop");

  var found = false;
  for (var j = 0; j < result.length; j++) {
    console.log("inside i loop");
    if (result[j].children.filePath == arr[i].children.filePath) {
      found = true;
      result[j].nodes = result[j].nodes.concat(arr[i].nodes);
      break;
    }
  }
  if (!found) {
    result.push(arr[i]);

  }
}

Your assistance is greatly appreciated.

Update: An issue arises when there are duplicate 'titanium' folders at the second level, causing folder repetition. See updated JSON data. Any advice on how to address this?

Answer №1

One effective strategy is to utilize a hashmap object with common property values as keys and corresponding full objects as the values

This simplifies the process by enabling quick lookups to determine if a key already exists. If it does, the current object can be merged with the one in the hashmap. The final merged results can then be retrieved from the hashmap

const tmp = {}

ParentObj.children.forEach((o) => {
  const path = o.data.filePath;
  if (tmp[path]) {
    tmp[path].children = tmp[path].children || [];// handling cases where no children property or array exists
    tmp[path].children.push(...o.children)
  } else {
    tmp[path] = o;
  }
});

ParentObj.children = Object.values(tmp);
console.log(ParentObj)
.as-console-wrapper {max-height: 100%!important;}
<script>
  const ParentObj = {
    "data": {
      "resTitle": "-JANAF Thermochemical Tables - SRD 13"
    },
    "children": [{
      "data": {
        "filePath": "borides"
      },
      "children": [{
        "data": {
          "filePath": "titanium"
        },
        "children": [{
          "data": {
            "filePath": "srd13_B-102.json"
          },
          "children": []
        }]
      }]
    }, {
      "data": {
        "filePath": "borides"
      },
      "children": [{
        "data": {
          "filePath": "zirconium"
        },
        "children": [{
          "data": {
            "filePath": "srd13_B-103.json"
          },
          "children": []
        }]
      }]
    }]
  }
</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

The HTML button triggers a function to execute on a different webpage when clicked

I'm facing a straightforward issue that I can't seem to figure out due to my limited experience with Angular and web development. The problem revolves around two components, namely home and dashboard. In the home.component.html file, there's ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

Using setInterval to update the content of a Text Area continuously

I am currently working on a script that involves extracting a string from a textarea, breaking it down into an array using the delimiter "=====\n", and then displaying each element of the array in the textarea every 250ms. However, I have noticed that ...

What is the best way to integrate ES6 ReactJS code into an Express application?

I am trying to initially render my ReactJS application on the server using ExpressJS. Although I have been able to import ES6 modules using require(), the module crashes upon loading because it contains ES6 code (ES6 import and export). Index Route var ...

Encountering unspecified values when subscribing to a BehaviorSubject and receiving it as an Observable

My goal is to display the name of the currently logged-in user in the header of my application. However, I encountered an issue where upon refreshing the page, the value would be lost due to SPA behavior (even though the data is stored in local storage). T ...

Using styled() in TypeScript to customize a Material UI List component

I am currently in the process of transitioning a project from JavaScript to TypeScript, and I have encountered an issue with a modified version of Material UI's List component that is created using style(). The specific problem arises when I attempt t ...

extract all elements from an array nested within another array

I am having difficulty extracting data from an array file in PHP. I was able to read it and convert it into a PHP array, but now I want to display the stored information in a table, however, I keep getting incorrect values. How can I retrieve the informat ...

Unexpected issue encountered while utilizing variadic function in Node.js

//##// Custom Output System //##// function output(type, ...strings) { var str = strings.join(' '); switch (type) { case "log": console.log("\x1b[37m", '[LOG]\t', str, "&bso ...

Determine whether there is text present on a webpage using JavaScript

I am familiar with Python coding from selenium import webdriver driver = webdriver.Chrome() driver.get('http://WEBSITE') assert 'TEXT' in driver.page_source However, I now require the equivalent JavaScript code. ...

Adjusting widths of strokes in React Native Vector Icons

I selected an icon from the react-native-vector-icon library. For instance, let's use featherIcons. How can I include a stroke-width property to the react-native-vector-icons package? import FeatherIcon from 'react-native-vector-icons/Feather&ap ...

How can I correctly annotate property 'firebase' on type '{ children?: ReactNode; }' in order to resolve the error?

My firebase object is provided through a higher order component as shown below: const FirebaseContextInterfaceLocal: FirebaseContextInterface = { value: new Firebase() } ReactDOM.render( <Router history={history}> <FirebaseContext.Provi ...

Utilizing a JavaScript-sent URL within a PHP data grid: A step-by-step guide

I am working on a JavaScript function that fetches the URL of an API needed for a data grid. This API displays the students assigned to a particular teacher. The data grid must dynamically change based on the user (the teacher initiating the session), and ...

Issue with formatting and hexadecimal encoding in JavaScript

I am currently developing a LoRaWAN encoder using JavaScript. The data field received looks like this: {“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547} My task is to encode this data into a hex message. Bel ...

Press anywhere else on the screen to dismiss the bootstrap menu

I've been attempting to find a solution for closing the Bootstrap menu when clicking outside of it in a mobile window size, but I just can't seem to make it work. I did manage to get it working when clicking one of the 'a' links using t ...

Update the element's state to display a collection of Components following an API request

Lately, I delved into learning Next.js and decided to first explore React and its various functionalities. One of the tasks I accomplished was creating a form that takes user input, interacts with an API, and returns a JSON Object to modify certain Compone ...

Press the "Reveal More" button to expand the content to its full size

I am currently working on coding a "read more" section using a button. I have looked at some existing solutions, but none of them are to my liking. My plan is to create a div that includes all the relevant content. My goal is to have a div at the bottom w ...

What is the behavior of the JavaScript event loop when a Promise's resolution is tied to setTimeout?

console.log('1') setTimeout(() => { console.log('2') }, 0) function three() { return new Promise(resolve => { setTimeout(() => { return new Promise(resolve => resolve('3')) },0) ...

Refresh the webpage content by making multiple Ajax requests that rely on the responses from the previous requests

I am facing a challenge where I need to dynamically update the content of a webpage with data fetched from external PHP scripts in a specific sequence. The webpage contains multiple divs where I intend to display data retrieved through a PHP script called ...

The warning message is "UnhandledPromiseRejectionWarning: TypeError: Unable to access the 'forEach' property of an undefined object in

I'm having issues with my Discord song bot because I can't seem to implement a working loop using either 'for' or a forEach. Currently, I am focused on making the loop function correctly, and once that's achieved, I will work on di ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...