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

Is it necessary to reset the variable following an ajax request?

There are two ajax functions in my code: $("body").on("click", ".follow", function() { var followingId = $(this).data("following"); var followData = {"following_id" : followingId} $(this).addClass('disabled'); $.ajax({ ur ...

Angular model remains static when incorporated within the document.addEventListener() attribute

Can anyone help me figure out why my attempt to update the model name this.name on click inside document.getElementById('source-selection').addEventListener is not working? Surprisingly, a simple alert within that function does trigger successful ...

Error: Could not locate module: 'path' in ' ode_modulessource-map-support' - npm

During the migration process from Angular 5 to Angular 7, I encountered a couple of errors such as map and forkJoin being deprecated. Thankfully, those issues were resolved. However, there is still one lingering error that crops up when running ng serve. ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Using Styled Components to achieve full width for input tag in relation to its parent

I am working with an input field that has a specific width set. My goal is to increase the width of this input field to 100% by selecting it from its parent component. Is there a way to achieve this without passing an explicit width prop in the styled c ...

What is the best way to transform typescript defined string types into an array of strings?

I'm attempting to extract all defined types from a variable in a constructor. export interface TestType { resultType?: 'NUMBER' | 'STRING' | 'DATE' | 'ENUM' | 'AMOUNT' ; } My expectation is to achie ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

Can you explain the significance of { 0: T } in this particular type definition?

I stumbled upon this type declaration in my codebase which is meant for non-empty arrays: type NonEmptyArray<T> = T[] & { 0: T } and it functions as expected: const okay: NonEmptyArray<number> = [1, 2]; const alsoOkay: NonEmptyArray<n ...

Using jQuery's ajax function to send a POST request

While following the MvcMusicStore tutorial, I decided to exercise my jQuery skills by converting a $.post() call to a $.ajax() call in order to remove an item from the shopping cart. However, I encountered a runtime error and am unsure about what went wron ...

personalized pagination feature within the jQuery bxslider module

Having trouble with jQuery and not sure where to begin. Utilizing the bxslider plugin for a carousel on my website. Below is a snippet of the HTML: <ul id="promos"> <li> <h2>Event Title 1</h2> </li> < ...

Storing various checkbox values into a database

I have a form with checkboxes that I need to submit to an API for database storage. This is the city.page.html <ion-item *ngFor="let city of cities;"> <ion-checkbox [(ngModel)]="city.id" ></ion-checkbox> <i ...

Keeping track of the toggle state using a cookie

While searching for a way to retain the toggle state, I stumbled upon js-cookie on GitHub. The documentation provides instructions on creating, reading, and deleting a cookie. However, an example would have been really helpful in enhancing my understanding ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

After a push to the router, scrolling is disabled

While working on a Vuejs project, I encountered an issue when trying to change the page of my PWA using this.$router.push();. It seems to work fine everywhere else except when doing it from a modal within a component. The pushed page loads but scrolling is ...

What is the best way to create a sticky menu bar?

I have this code snippet at the beginning of my website: <body> <div class="agile-main"> <div class="menu-wrap" id="style-1"> <nav class="top-nav"> <ul class="icon-list"> ...

Access your login page with a nodejs mongoDB connection

After successfully sending username, password, and email through postman, the information gets added to the MongoDB schema. However, on the login page in React, it doesn't seem to work correctly. Any assistance would be greatly appreciated. Thank you. ...

Can PassportLocalDocument and PaginateModel coexist within the same framework?

I am new to TypeScript and NestJS, looking to implement a pagination feature for all models in my application. Currently using NestJS with Mongoose for the API project. Here is an example of the user schema: export const UserSchema = new mongoose.Schema( ...

How to interrupt a JQuery animation and restart it from the middle?

Currently, I am tackling my first JQuery project and facing a challenge. As the user mouseleaves the .container, the animation does not reset but continues as if they are still within it. My goal is to have the animation revert in reverse if the user decid ...

When clicking on the material-ui autocomplete feature in a React JS application, a blank page unexpectedly opens

I am encountering a problem where, upon clicking the Autocomplete component imported from material-ui, it displays a blank page. const defaultProps = { options: catalogs, getOptionLabel: (option) => option.catalogsLink, }; <Autocomplet ...

"Utilizing the datepicker functionality in Rails with jQuery UI

I am looking to integrate the datepicker widget into one of my select fields within a Rails 3.2.13 application with Ruby 1.9.3.p325 installed. To achieve this, I have incorporated the 'jquery_datepicker' gem along with 'jquery-rails' an ...