What is the best way to insert an object at a particular position within an array containing numerous nested objects?

This is the given Object:

[
    {
        "id": "1709408412689",
        "name": "WB1",
        "children": [
            {
                "id": "1709408412690",
                "name": "WA X",
                "children": [
                    {
                        "id": "1709408412687",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1709408606635",
                        "name": "Lph 1",
                        "children": []
                    }
                ]
            },
            {
                "id": "1709408412691",
                "name": "WA 1",
                "children": [
                    {
                        "id": "1709408679357",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1709408679358",
                        "name": "Lph 1",
                        "children": []
                    },
                    {
                        "id": "1709408679359",
                        "name": "Lph 2",
                        "children": [
                            {
                                "id": "1709308679359",
                                "name": "Lph 2.2",
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Now I have the following information (4 details):

{newID: 1509408679357
name: 'INSERTHERE',
typeToInsert: 'before' (before or after)
placeToInsert: '1709408679358' }

I want to add a new object before (typeToInsert: 'before') the object with ID: '1709408679358' (placeToInsert).

I attempted various methods, but since the objects can be nested multiple times, I believed using a recursive function was necessary. Unfortunately, my attempts were unsuccessful.

Desired Outcome:

[
    {
        "id": "1709408412689",
        "name": "WB1",
        "children": [
            {
                "id": "1709408412690",
                "name": "WA X",
                "children": [
                    {
                        "id": "1709408412687",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1709408606635",
                        "name": "Lph 1",
                        "children": []
                    }
                ]
            },
            {
                "id": "1709408412691",
                "name": "WA 1",
                "children": [
                    {
                        "id": "1709408679357",
                        "name": "B-Plan",
                        "children": []
                    },
                    {
                        "id": "1509408679357",
                        "name": "INSERTHERE",
                        "children": []
                    },
                    {
                        "id": "1709408679358",
                        "name": "Lph 1",
                        "children": []
                    },
                    {
                        "id": "1709408679359",
                        "name": "Lph 2",
                        "children": [
                            {
                                "id": "1709308679359",
                                "name": "Lph 2.2",
                                "children": []
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

Answer №1

The new code snippet here is designed to find the appropriate array where a new object needs to be inserted, using recursion.

It starts by checking if the current array has a child with the required ID. If not, it uses reduce method to search for a nested array containing an object with that ID.

After identifying the target array, it utilizes the splice function to insert the new object. When inserting after instead of before, an additional 1 is added to the index after locating the insertion point based on true/false coercion to 1/0.

const data = [{"id":"1709408412689","name":"WB1","children":[{"id":"1709408412690","name":"WA X","children":[{"id":"1709408412687","name":"B-Plan","children":[]},{"id":"1709408606635","name":"Lph 1","children":[]}]},{"id":"1709408412691","name":"WA 1","children":[{"id":"1709408679357","name":"B-Plan","children":[]},{"id":"1709408679358","name":"Lph 1","children":[]},{"id":"1709408679359","name":"Lph 2","children":[{"id":"1709308679359","name":"Lph 2.2","children":[]}]}]}]}

const update = {newID: 1509408679357, name: 'INSERTHERE', typeToInsert: 'before', placeToInsert: '1709408679358'}

const getTargetArray = arr => arr.some(({id}) => id===update.placeToInsert) ? 
  arr : arr.reduce((a, {children}) => a ?? getTargetArray(children), null)

const targetArray = getTargetArray(data)

targetArray.splice(
  targetArray.findIndex(({id}) => id === update.placeToInsert) 
    + (update.typeToInsert === 'after'), 
  0, 
  {id: update.newID, name: update.name, children: []}
)

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

Having difficulty connecting to Facebook's graph API through node.js

Here is the specific URL I am attempting to access: https://graph.facebook.com/v2.8/me?fields=friends?access_token=xxxx. The desired outcome should match what is seen on Graph API Explorer: { "friends": { "data": [ ], "summary": { " ...

Ensuring that the empty bubble remains undisturbed, here's a guide on effectively implementing the if

I need assistance with adding an "if condition" to my text field. The condition should prevent the empty bubble from appearing when the send button is clicked. function verifyInput(){ var currentText = document.getElementById("demo").innerHTML; var x ...

Contrast between utilizing filter_input and accessing $_POST directly following an asynchronous AJAX request

When I use filter_input(INPUT_POST, 'attribute') and $_POST['attribute'], I get different results and I can't figure out why. The Post-Request is sent by a JavaScript script built with JQuery and it looks like this: // type javaS ...

Encountering node-gyp build issues on a Mac while trying to install npm packages can be frustrating. The error message that states "`

I am currently facing an issue with setting up my Vue.js app on my Mac machine locally. When I try to install the dependencies using npm install, I encounter the following error: npm ERR! 1 error generated. npm ERR! make: *** [Release/obj.target/binding/sr ...

Concerns arise when code alters the file structure during deployment

My application needs to parse through data from a site that provides a JSON file in a tar.gz format. The current code sends a request to the site, downloads the tar.gz file, extracts the JSON content, and then parses it. However, I have not integrated thi ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

Transforming the String Values in an Array to Capitalize the First Letter of Each Word Using VueJS

After receiving an array of objects from an API call: "data": [ { "heading_one_of_the_table": 14, "total": 8 }, { "heading_one_of_the_table": 1, "total": 7 }, { "heading_one_of_the_table": 6, "total": 7 } ] I want to ...

Obtaining Compiled HTML Output Using AngularJS

I'm running into an issue with obtaining the compiled html of a page in AngularJS. Below is the code snippet that demonstrates this problem: JavaScript: <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script> &l ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

Having trouble with executing Athena query using athena-express when using req.body as input

Seeking guidance on querying specific data from AWS Athena using req.body parameters. When attempting to execute the query with req.body in postman, encountering the following error: Error: SYNTAX_ERROR: line 1:1: Incorrect number of parameters: expected 1 ...

Does a DOM API exist specifically for querying comment nodes within the document?

My document contains a debugging comment that appears as follows: <!--SERVER_TRACE {...}--> Is there a method to search the DOM and access this specific node? I would prefer a vanilla JavaScript solution, without relying on any external libraries. ...

Fetching the second item within an object using JavaScript

I am trying to retrieve the data from the last month of an API, but I want to avoid hard-coding the date like this: const data = [data.data['Monthly Time Series']['2021-11-30']]. I need a way to dynamically access the 2nd object without ...

`Multiple files processing with Gulp`

I am currently in the process of developing a Gulp task that will minify a CSS file for each project's CSS. For example, Project A will have its files combined and minified as follows: global.projecta.css tool1.projecta.css tool2.projecta.css I beli ...

Adding a component to a slot in Vue.js 3

My Goal I aim to pass the Component into the designated slot. The Inquiry How can I effectively pass the Component into the slot for proper rendering? It works well with strings or plain HTML inputs. Additional Query If direct passing is not feasible, ...

"Integrate information from a Node.js source into an already existing HTML document

I am new to node.js and have a question regarding my server.js file: var express = require('express'); var cors = require('cors'); var app = express(); var path = require('path'); var request = require('request'); v ...

Enhance user experience with AngularJS Bootstrap autocomplete feature by automatically filling input box when hovering over dropdown options

I am currently implementing the AngularJs Bootstrap typeahead functionality. Typically, when we enter text that matches an option, the dropdown list appears. https://i.stack.imgur.com/395Ec.png What I aim for is to automatically fill the textbox with the ...

Learn the process of sending notifications upon clicking on an advertisement by a user

I'm currently working on a system that displays ads on mobile devices. Our clients have the option to use their own custom HTML code for their advertisements. We want to be able to track when a user clicks on these ads. I am considering wrapping the u ...

Resolving issues with PHP JSON format error in array formatting

This is the MySQL script I am working with: $result = mysql_query("SELECT users.*,games.game_names,games.id AS games_id FROM users LEFT JOIN games ON FIND_IN_SET(games.id,users.games)") or die(mysql_error()); while($user = mysql_fetch_array($result, MY ...

Expanding the functionality of Element.prototype, problem related to anchor

Consider the following code: A JavaScript (JS) Snippet Element.prototype.changeInnerText = function(str) { this.textContent = str; return this; } let divElement = document.createElement('div').changeInnerText('new div text'); / ...