Utilizing indexes to incorporate elements into an object array

I'm currently working on a project using Angular. I have an index coming from the HTML, and here is the code snippet:

save(index){
//this method will be called on click of save button
}

In my component, I have an array structured like this:

data = [{
 "name":"Rosy"
},
{
 "name":"julia"
}]

Within the save method, I want to add a subarray for the index that I receive. For instance, if I receive index 0, I would like to add a subarray at the 0th index in the data array, resulting in:

data = [{
 "name":"Rosy",
  "Address":[{
    "city":"London" // the city value is sourced from a component variable
  }]
},
{
 "name":"julia"
}]

If I receive index 0 again, with the city now being "Mumbai," the data will be updated as follows:

data = [{
     "name":"Rosy",
      "Address":[{
        "city":"London" 
      },
      {
        "city": "Mumbai"
      }
]
    },
    {
     "name":"julia"
    }]

This process is repeated for other indexes and elements. How can I achieve this?

Answer №1

If you're looking to streamline this process, here is a simple function that can help:


let cityData = {"city" : "Mumbai"};

//array containing your data

let updateCity = (index) => {
  let element = data[index];
  if(element["Address"]!=undefined){
    element["Address"].push(cityData);
  }
  else{
    element["Address"] = [cityData];    
  }  
}

Given that your data is an array of objects, this function takes one element from the array and updates it directly. The changes will be reflected in the original array. Make sure the index provided is within bounds, and feel free to customize this function to suit your specific requirements.

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

Focusing on an input element in Angular2+

How do I set focus on an input element? Not with AngularDart, but similar to the approach shown in this question: <input type="text" [(ngModel)]="title" [focus] /> //or <input type="text" [(ngModel)]="title" autofocus /> Does Angular2 provi ...

Implementing a loop in jQuery is not functioning as expected

Can someone help me figure out how to use a for loop to create a jQuery function? I'm having trouble when adding the array parameter in the string, it just doesn't seem to work correctly. Any suggestions? var ids=["width_uncheck","thickness_unch ...

Combining arrays using value comparison in Google Analytics and MongoDB

Help me out, Stack! This job is driving me crazy. Here's what I'm working on: Using the Google Analytics NodeJS SDK, I'm retrieving data about the most visited pages of my website. By leveraging Google's user-friendly URLs (slugs), I se ...

Having trouble pushing data to a GraphQL database from my Next.js application

I am currently working on developing a Reddit-like platform. To simplify the process, I have integrated SQL with graphQL using Stepzen for endpoints. Below is the code snippet of my Post Box component for the site, which includes graphQL mutations.ts and q ...

Slim 4 with Angular 10: Issues with downloading PDF files through API, as Angular blob response is coming back empty

Struggling to integrate the download PDF Angular API with Slim 4 API. The response from Slim can be seen in the browser network, but when trying to parse it in Angular, it comes back empty. All the necessary headers have been added on both Angular and Slim ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

Use contextual type when determining the return type of a function, rather than relying solely on

When using Typescript 2.2.2 (with the strictNullChecks option set to true), I encountered an unexpected behavior. Is this a bug or intentional? interface Fn { (value: any): number; } var example1: Fn = function(value) { if (value === -1) { ...

The response from my reducer was a resounding "never," causing selectors to be unable to accurately detect the state

Currently utilizing the most recent version of react. I am attempting to retrieve the state of the current screen shot, but encountering an error indicating that the type is an empty object and the reducer is "never". I am unable to detect the state at all ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

I noticed that while my shareService is effectively sending values in Angular 2, I encounter an issue where my other components are displaying default values instead

I'm in the process of developing an application using angular 2. I have a UserService that sends a value to other components indicating whether a user is logged in or not, and it's working correctly in terms of data transmission. The issue I&apos ...

Is it possible for TypeScript to automatically determine the specific type that was used in a union type parameter?

I need some help with a utility function I'm working on that can remove a specified number of elements from either a string or an array. My goal is to have the compiler determine whether the return value should be a string or an array based on what is ...

Troubles encountered while trying to make MediaRecorder function in Angular 9

Recently, I've been working on integrating Media Recorder into my Angular 9 application by following the instructions provided at this link. However, I have encountered some issues along the way. When I access the page with the Media Recorder compone ...

How can I compel npm to resolve dependencies flatly?

I am working on a project where multiple frontends share a common library. The module dependencies for these projects are managed using npm. In the package.json file of each project, I specify: "dependencies": { "mylib": "file:../<...path...> ...

The data type 'string | boolean | null' cannot be assigned to type 'boolean'. Specifically, the type 'null' cannot be assigned to type 'boolean'

Can you spot the issue in this code snippet? isAuthenticated(): boolean { var token = localStorage.getItem(ACCESS_TOKEN_KEY); return token && !this.jwtHelper.isTokenExpired(token); } Error: The variable is returning a type of 'string | bo ...

What is the best way to bring in an array from a local file for utilization in a Vue 3 TypeScript project?

Encountering a TS7016 error 'Could not find a declaration file for module '../composables/httpResponses'. '/Users/username/project/src/composables/httpResponses.js' implicitly has an 'any' type.' while attempting to ...

What is the best approach for integrating a Material UI Autocomplete component with graphql queries?

Hello there! I'm currently working with React Typescript and trying to incorporate query suggestions into an Autocomplete Material UI component in my project. Below is a snippet of my GraphQL queries: Query Definition: import gql from 'graphql- ...

Troubleshooting Issue with Angular Property Binding for Image Dimensions

Currently, I am exploring property binding in Angular through an example. The idea is to use an image and bind its width, height, and src attributes using property binding. Surprisingly, even though there are no errors and the image renders successfully vi ...

Update CSS using onChange event with an array of values

I'm currently working on an app that allows users to select a color scheme from a dropdown form. The hexidecimal values associated with the selected color scheme successfully populate specific text fields as intended. However, I am facing difficulty i ...

Is there a way to enable autofill functionality if an email already exists in the database or API within Angular 12?

In order to auto-fill all required input fields if the email already exists in the database, I am looking for a way to implement this feature using API in Angular. Any guidance or suggestions on how to achieve this would be greatly appreciated. ...