Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met.

Let me share the code snippet with you:

RequestObj = [{
    "parent1": {
        "ob1": value,
        "ob2": {
            "key1": value,
            "key2": value
        },
    },
},
{
    "parent2": {
        "ob1": value,
        "ob2":{
            "key1":value,
            "key2": value
        }
    }
}]

In this scenario, I need to include another object in the RequestObj array based on certain conditions. While I am familiar with using RequestObj.push(), I am unsure how to add it within the parent1 object.

if (key3 !== null) {
    // Include the following object inside parent1 object
    "ob3": {
        "key1": value,
        "key2": value
    }
}

Despite my efforts, I have not been able to come up with a solution for this issue. Your assistance would be greatly appreciated.

Answer №1

One method to add an element to an array is by using the push function.

// Create a new object
var newObject = {
    "ob3": {
        "key1": value,
        "key2": value
    }
};
// Add the new object to the array
RequestObj.push(newObject);

You can also directly push an object into the array without declaring a variable first:

// Add new object to array
RequestObj.push({
    "ob3": {
        "key1": value,
        "key2": value
    }
});

UPDATE

If you are not just pushing into the array but adding a new property to an object inside the array, you must be aware of the position of the element within the array (such as RequestObj[0] for the first element).

Then, within that element, you have to add a new property to the parent1 object (RequestObj[0].parent1):

RequestObj[0].parent1.ob3 = {
      "key1": "A",
      "key2": "B"
 };

var RequestObj = [{
  "parent1": {
    "ob1": "A",
    "ob2": {
      "key1": "B",
      "key2": "C"
    },
  },
  "parent2": {
    "ob1": "D",
    "ob2": {
      "key1": "E",
      "key2": "F"
    }
  }
}];

var key3 = 'somethingNotNull';

if (key3 !== null) {
  RequestObj[0].parent1.ob3 = {
      "key1": "A",
      "key2": "B"
  };
}
console.log(RequestObj);

Answer №2

To search for the object with key parent1 in the loop using RequestObj, you need to iterate through it.

You can achieve this by utilizing the .filter method as shown below:

for(let i = 0; i < RequestObj.length; i++) {
   let found_object = RequestObj[i].filter(function (r) {
      return r === 'parent1'
   });
}

After finding the object, you can then perform operations on found_object.

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 initial setTimeout function functions correctly, however the subsequent ones do not operate as expected

I have developed the following code: bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here' ...

Retrieve the id by using the `$` selector

I am trying to achieve the following in my code : <table> @foreach(var foo in Model.List) { <tr> <td><a href="#" class="MnuCustomerSelect" id="@foo.Id">Select</a></td> <td>@foo.Id</td> ...

Is there a way to effectively leverage jquery(window.load) within Casperjs?

My Unique Script var ghost = require('phantom').create({ clientScripts: [ '/Path/to/Javascript/Test/jquery-3.5.1.js' ], logLevel: "error", logLevel: "warn", verbose: false }); ghost.start("http://www ...

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Navigating through Vue Router with Dynamic Imports and Guards

I am looking to dynamically bring in data from a component file into a router file, and then allow the use of next() based on the value of the imported data. In my App.vue file, I am using this.$router.push({name: "Dashboard"}) when the data changes from ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

Redirect the Submit button to the specified URL from the form element

Looking for a way to create a form with two fields: Username and Password. Upon clicking submit, the username and password should be added to the URL in a specific format. For instance: The URL structure will remain the same, only the "username_entered_i ...

Tips for sending two values to a PHP file using JavaScript Ajax

I have created a code for two dropdown menus. The goal is to select values from both menus and send them to a php file using the GET method. The values should be sent to the php file only when both menus have selections made. Below is the code snippet: ...

tslint is flagging an error related to cyclomatic complexity

Within my Angular 8 project, the following dependencies are utilized: "codelyzer": "^5.1.0", "ts-node": "~8.3.0", "tslint": "~5.19.0", Upon executing: ng lint myapp --fix=true An error is raised stating: ERROR: ...html:428:106 - The cyclomatic complex ...

Customizing the default settings of a d3 funnel chart

I recently used the following link to create a funnel chart using D3: jakezatecky/d3-funnel Everything was working perfectly. However, I wanted to adjust the block heights in proportion to their weight as mentioned in the tutorial by changing the D3 defau ...

Whoops! Looks like there was a hiccup with the Vercel Deployment Edge Function, causing an

Every time I attempt to send a POST request to my Edge Function on Vercel Deployment, I encounter the following error message: [POST] /api/openai reason=EDGE_FUNCTION_INVOCATION_FAILED, status=500, user_error=true TypeError: Illegal invocation at app/api/ ...

Steps for choosing the nth HTML row with jQuery

I'm facing a situation where I need to be able to select the nth row of an HTML table based solely on the id of the selected row. You can see exactly what I mean by checking out this JSFiddle Demo <table class="mytable1"> <tr><td i ...

Persistence of query parameters from old routes to new routes using vue-router

Whenever a query parameter called userId is present in a route within my application, I want the subsequent routes to also include this query parameter. Instead of manually modifying each router-link and router.push, I am looking for a solution using rout ...

What steps can be taken to eliminate a npm install error?

I have been attempting to execute the following project: https://github.com/kentcdodds/react-in-angular This repository serves as an illustration of incorporating React into AngularJS. It consists of three tags that demonstrate the process of transitio ...

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...

What is the best way to effectively adjust the code structure in a Node.JS project?

[Summarized] Focus on the bold parts. Although I am relatively new to Node.JS, I have been able to successfully build some projects. However, I have come across a burning question that has left me frustrated after searching Google for answers without much ...

Performing calculations using jQuery and organizing sub-totals into groups

I am currently developing a web application and aiming to incorporate an invoice calculation feature with sub-groups. My goal is to have the total result of both group-totals and sub-totals at the end. Here is my progress so far: Check it out here $(func ...

Using Node.js to retrieve child processes associated with a daemon and terminate them

I am attempting to create a node application that allows me to send the command kill -9 to all child processes of a single daemon. Just to clarify, there is one daemon running on our server. Upon startup, it initiates a process for communicating with clie ...

Exploring Navigation States with JQuery: Active, Hover, and Inactive

I've been struggling with the code below as it doesn't seem to be working. I had a simpler code before for swapping images, so if there's an easier way to achieve this, I'm open to suggestions. Just to recap, I'm trying to: 1. La ...

Tips for effectively implementing Ajax functionality within a table grid

As someone who is fairly new to programming, I have a question regarding implementing basic operations in a grid table. Should I use AJAX for these operations or can I achieve them without it? In the grid, each record has operations such as view, edit, up ...