Locate and embed within a sophisticated JSON structure

I have an object structured as follows:

interface  Employee {
id: number;
name: string;
parentid: number;
level: string;
children?: Employee[];
}

const Data: Employee[] = [
{
id:1,  name: 'name1', parentid:0, level: 'L1',
children: [
  { id: 2, name: 'name2', parentid:1, level: 'L2'},
  { id: 3, name: 'name3', parentid:1, level: 'L2',
children: [
  {id: 4, name: 'name4', parentid:3, level: 'L3'}
]}
]
}
];

In this structure, the children's parentid corresponds to the parent data's 'id'.

If new data with [id=5, name:'name5', parentid=0 and Level='L1'] is provided along with its child data [id=6, name='name6'], we need to check if the given id=5 exists in L1. If not, it should be added like so:

[
{
id:1,  name: 'name1', parentid:0, level: 'L1',
children: [
  { id: 2, name: 'name2', parentid:1, level: 'L2'},
  { id: 3, name: 'name3', parentid:1, level: 'L2',
children: [
  {id: 4, name: 'name4', parentid:3, level: 'L3'}
]}
]
},
{
id:5,  name: 'name5', parentid:0, level: 'L1',
children: [
  { id: 6, name: 'name6', parentid:5, level: 'L2'}
]  
}
];

If a new entry with id:7, name:'name7', and parentid=3 is encountered, then it should be placed under the data with id 3 as shown below:

[
{
id:1,  name: 'name1', parentid:0, level: 'L1',
children: [
  { id: 2, name: 'name2', parentid:1, level: 'L2'},
  { id: 3, name: 'name3', parentid:1, level: 'L2',
children: [
  {id: 4, name: 'name4', parentid:3, level: 'L3'},
  {id: 7, name: 'name7', parentid:3, level: 'L3'}
]}
]
},
{
id:5,  name: 'name5', parentid:0, level: 'L1',
children: [
  { id: 6, name: 'name6', parentid:5, level: 'L2'}
]  
}
];

Please provide guidance on this matter.

Answer №1

To achieve the desired outcome, you must iteratively search for the parent and add the data to the children array if it exists.

Within the code snippet below, you can experiment with commenting out or uncommenting different findParent function calls and console logs.

const data = [{
  id: 1,
  name: 'name1',
  parentid: 0,
  level: 'L1',
  children: [{
      id: 2,
      name: 'name2',
      parentid: 1,
      level: 'L2'
    },
    {
      id: 3,
      name: 'name3',
      parentid: 1,
      level: 'L2',
      children: [{
        id: 4,
        name: 'name4',
        parentid: 3,
        level: 'L3'
      }]
    }
   ]
}, {
  id: 5,
  name: 'name5',
  parentid: 0,
  level: 'L1',
  children: [{
    id: 6,
    name: 'name6',
    parentid: 5,
    level: 'L2'
  }]
}];

const insertData = {
  id: 7,
  name: 'name7',
  parentid: 3,
  level: 'L3'
};
const insertDataTwo = {
  id: 10,
  name: 'name7',
  parentid: 5,
  level: 'L3'
};

function findParent(data, parent) {
  data.forEach(item => {
    if (item.id === parent.parentid) {
      if (item.children) {
        item.children = [...item.children, parent]
      } else {
        item['children'] = [parent];
      }
    } else {
      if (item.children) {
        findParent(item.children, parent);
      }
    }
  });
}

//findParent(data, insertData);

//console.log(data);

findParent(data, insertDataTwo);

console.log(data);

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

Angular2 Cache: Enhance Your Application's Performance

Currently seeking a cache solution for my Angular2 application. Imagine we have a massive collection of Movie objects stored on a server, too many to fetch all at once. The server offers a REST endpoint: getMovie(String id) On the client side, I need a s ...

Set the value of request.json in flask as a json object

Typically, request.json is utilized to access JSON objects sent to a Flask view. I am interested in assigning a value to request.json. from flask import request print("request.json = ", request.json) print("request.form['json'] = ", request.form ...

Sending data using JSON and HTTP POST method via URL

Is it possible for my servlet to receive 4 parameters through HTTP POST by using a URL? An illustration of the URL: http:///servlet The data that will be delivered will be in text form utilizing the JSON format. JSONObject myStr = new JSONObject(); I a ...

Do not generate authentication code in JHipster using the --skip-server flag

Is there a reason why the authentication part is lost when generating a project with '--skip-server'? yo jhipster --skip-server It seems that upon generating the project without the server, the authentication gets affected (on AJS/A2). Is thi ...

Is it true that Angular 16 does not have compatibility with the ng search filter feature?

Is it true that Angular 16 does not support the ng search filter? I encountered an error when trying to implement it, saying "the library (ng2-search-filter) which declares Ng2SearchPipeModule is not compatible with Angular Ivy". Looking for suggestions o ...

Dependency mismatch in main package.json and sub package.json

Imagine you have a project structure in Typescript set up as follows: root/ api/ package.json web/ package.json ... package.json In the main package.json file located in the root directory, Typescript is installed as a dependency to make ...

Error: Unable to locate Angular2 Custom Service

I have implemented a custom service to populate a list of people in my HTML. Below is the code for my custom service: app.peopleListService.ts import { Injectable } from '@angular/core'; import { Person } from "../model/peopleModel"; @Injecta ...

"Encountered an issue while running the clean-css script in npm build

Encountering a peculiar error while running npm run build:prod today. "build:prod": "ng build --prod --aot=false --preserve-symlinks" The error message reads: 92% chunk asset optimizationC:\Projects\Latest_Feb26\ASSURE.OdyssEYGen2\Fr ...

Decoding a changeable JSON structure

As I am working on parsing a JSON and looking for a specific key within the JSON object, I am facing an issue due to the changing structure of the JSON. It is not feasible to hard code the path for searching. Are there any alternative methods to parse this ...

Troubleshooting error messages in Angular related to scss ModuleBuild

I've been working on applying a theme to my Angular application, but I've run into an issue. It seems that the src/theme.scss file I created is functioning correctly on its own. However, when I try to import "~@angular/material/theming", I encoun ...

IntelliJ does not provide alerts for return type inconsistencies in TypeScript

During the development of our web application using react+typescript+spring boot with IntelliJ, everything seemed to be going smoothly until I came across an unexpected issue. Take a look at this code snippet example: export class TreeRefreshOutcome { } e ...

What is the best way to transfer information between two React.js files?

I am currently finding it inefficient to pass data from App.js to another .js file within React by constantly reading and writing from local storage. I would prefer to only retrieve data from local storage once when the App.js component mounts. App.js: ...

Error: No routes found in Angular 5

I have developed an Angular 5 app and set up the following routing configuration in app-routing.module.ts file: import { ControlPanelComponent } from './dashboard/control-panel/control-panel.component'; import { MainComponent } from './dash ...

Enhancing Go Json Rest with Query Parameters

Currently, I am utilizing the go-json-rest library. My goal is to extract query parameters from my code when a URL like localhost:8080/reminders?hello=world is used. I want to be able to access {hello: world}. Below is the snippet of code I am using: //in ...

The concept of Border-Merging within Material Design Tables

Is there a way to implement the following border style in a Material Design Table: border-collapse: collapse; I tried adding a border to .mat-cell: .mat-cell { border: 1px solid; } However, in some instances, the border appears to be 2px. The reas ...

Extracting data from JSON in golang

I am working on a code snippet that utilizes the Yahoo Finance API to fetch stock values based on the provided stock symbol. package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "os" ) //Response structure type Response ...

Silencing the warning message from ngrx/router-store about the non-existent feature name 'router'

After adding "@ngrx/router-store" to my project, I noticed that it fills the app console in development mode and unit test results with a repeated message: The warning states that the "router" feature name does not exist in the state. To fix this, make ...

Having difficulty with JSON parsing in Xcode using Swift and Alamofire

Currently, I am in the process of constructing a Xcode project using Swift but have encountered an issue that is preventing me from completing it. I would greatly appreciate any suggestions or solutions that you may have to help me overcome this obstacle: ...

Retrieve the duration of a video from the YouTube API by utilizing JSON

I am currently working on a project where I need to retrieve and display the duration of each video returned by the Youtube API in JSON format. The duration should be displayed in a format like this: 9:34min instead of in seconds However, I am struggling ...

Is jQuery capable of appropriately escaping my quotes?

Currently, I am utilizing $.cookie() to retrieve all the values from a cookie which are stored in JSON format: var properties = $.cookie('params'); The output of properties is: {"distinct_id": "13f97d6600b42e-000e6293c-6b1b2e75-232800-13f97d66 ...