Insert the object into a designated location within a multi-dimensional array

I've integrated a tree view into my Angular project and I'm looking to add an object to a specific position within an array.

array

const TREE_DATA: TreeNode[] = [{"name":"Demo","id":"demo_1","children":[{"name":"Folder","id":"folder_1","children":[{"name":"File","id":1},{"name":"Doc","id":2}]},{"name":"Folder 2","id":"folder_2","children":[{"name":"doc file","id":3},{"name":"word","id":4}]}]},{"name":"Projects","id":"pro_1","children":[{"name":&...
const obj = { name: 'information', id: 50 }

and expected is

[{"name":"Demo","id":"demo_1","children":[{"name":"Folder","id":"folder_1","children":[{"name":"File","id":1},{"name":"Doc","id":2}]},{"name":"Folder 2","id":"folder_2","children":[{"name":"doc file","id":3},{"name":"word","id":4}]}]},{"name":"Projects","id":"pro_1","c...

How do I insert the object at a specific position based on its Id in the array?

Answer №1

Hey @DanteDX, I was hoping for something like the code snippet below. It seems my question may have been a bit unclear, as I didn't receive a response from you.

private performSearch(items: TreeNode[], term: string): any[] {
        return items.reduce((acc: TreeNode[], item: TreeNode) => {
            if (this.checkIfContains(item.name, term)) {
                acc.push(item);
            } else if (item.children && item.children.length > 0) {
                let newItems = this.performSearch(item.children, term);
                if (newItems.length > 0) {
                    acc.push({ ...item, children: newItems });
                }
            }
            return acc;
        }, []);
    }

    private checkIfContains(text: string, term: string): boolean {
        return text.toLowerCase().indexOf(term.toLowerCase()) >= 0;
    }

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

Turn off the feature that highlights links

Hi there! I'm curious to know if it's feasible to remove the highlighting effect when clicking on a link. I'd like the link to function more like an image, without the appearance of a highlighting box upon clicking. ...

Restrict the maximum and minimum time that can be entered in an HTML input

I've implemented a basic code feature that allows users to input minutes and seconds on my React website. <div> <span> <input defaultValue="0" maxlength="2"/> </span> <span>m</span> <spa ...

After clicking on the About page in Vue, my data seems to vanish into thin air

The Vue router is up and running with two pages: Home and About. Everything seems to be functioning properly, however, when I navigate to the About page and then return to the Home page, the data is lost. The page isn't refreshing, I'm simply swi ...

The Vue CLI build is displaying a blank page when hosted on an Apache server

I encountered an issue with vue cli. Running npm run serve went smoothly, but when I tried dev mode using npm run build-dev, the build process finished with a blank page displayed. The error message received was "Uncaught SyntaxError: Unexpected token &ap ...

Uploading a CSV file in JSON format to Amazon S3 with Node.js

Within my nodejs server.js script, the following code snippet can be found: router.post('/submission', (req, res) => { let data_filtered = req.body.data }) Upon user submission of a csv file, I am successfully retrieving it on the backend. ...

Exploring the Interplay of Classic ASP and AJAX Variables References

When the page loads, I check for an empty session variable. If it is empty, I trigger an AJAX function to include a hidden login form with ASP script that becomes visible through JavaScript. This part of the process works smoothly. Upon submitting the for ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...

trigger a p:ajax event by employing a right-click action

Currently, I am utilizing JSF and Primefaces 5.2. A peculiar observation I made is that when a commandLink is used with the onclick event and p:ajax, it creates a selection effect. <h:commandLink id="commandLink"> <p:ajax event="click"/> </ ...

What is the process for incorporating an additional input in HTML as you write?

I am looking to create a form with 4 input boxes similar to the layout below: <input type="text" name="txtName" value="Text 1" id="txt" /> <input type="text" name="txtName2" value="Text 2" id="txt" /> <input type="text" name="txtName3" valu ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Is there a way to retrieve a numerical value from within two specific elements when web scraping?

I am new to web scraping and looking to extract the numbers located between the strong tags. Currently, I am using Python 3.8 along with BeautifulSoup for this task. <li class="price-current"> <span class="price-current-label"> </s ...

What purpose does the symbol '$' serve in React component properties?

While delving into the world of styled-component, I encountered some difficulties with the 'adapting based on props' aspect. import './App.css'; import styled from 'styled-components' const PrimaryButton = styled.button` co ...

What steps do I need to take in order to activate scrolling in a Modal using Material-UI

Can a Modal be designed to work like a Dialog with the scroll set to 'paper'? I have a large amount of text to show in the Modal, but it exceeds the browser window's size without any scrolling option. ...

Tips for utilizing a personalized design with the sort-imports add-on in VS Code?

After recently installing the VS Code extension sort-imports, I decided to give a custom style called import-sort-style-module-alias a try. Following what seemed to be the installation instructions (via npm i import-sort-style-module-alias) and updating m ...

How can I make a basic alert box close after the initial click?

After clicking a button, I have a simple jQuery script that triggers a fancybox. However, the issue is that the fancy box does not close after the first click of the button; it only closes after the second click... Another problem arises inside the fancy ...

Ways to verify if the inner <div> contains any text

I am attempting to determine if the inner <div> contains the text "Ended" and then remove it if it does. There are multiple <div> elements with the same class. I have attempted to use the .filter() method. My goal is to remove the container_one ...

Error code 12030: AJAX request status

When making an ajax XMLHttpRequest using the POST method, I am encountering a readyState of 4 with a status of 12030. It is known that 12030 is a Microsoft-specific state code indicating that the connection was not sustained. However, I have been unable to ...

Show information from the state using React and Typescript

I successfully retrieved data from an API using axios and stored it in the state of my React component. However, I am struggling to display this data on the web so that I can list all the information obtained from the API request. I have tried using the ma ...

Is it possible to update both package-lock.json and package.lock simultaneously?

Before releasing to NPM, I always make sure to update the minor version. My usual process includes: - Modifying the package.json - Executing npm i to synchronize package-lock.json with the changes. This prepares both files for publishing. Is there a simpl ...

What is the process for eliminating the invocation of a function in Jquery?

I am currently facing an issue with my application. When I launch the Ficha() function, it initiates an ajax call and works perfectly fine. However, another ajax call is made later to load HTML tags that also need to invoke the Ficha() function. The prob ...