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

Converting JSON data into GeoJSON format using JavaScript

Currently, I am in the process of reading a JSON file and formatting it for GeoJSON function getAddress(id,search,vagas, next) { geo.geocode({address:search}, function (results,status) { if (status == google.maps.GeocoderStatus.OK) { ...

Manipulating Strings in JavaScript Arrays

I am working with an array of arrays of data that is being retrieved from a csv file. My goal is to filter out specific indexes of an array based on the titles they contain. For instance: If an array index includes the title "Retail", I want to return the ...

Reserve memory for an array of fixed-size arrays dynamically

After reading numerous posts on this topic, it seems that my issue is a bit more specific. I am attempting to allocate a dynamic 2D array. Due to restrictions in the existing code, I need to use a typedef for a static array. However, now I need to tempora ...

Incorporated iframe covering the entire browser window

Currently, I find myself in a strange predicament. The scenario involves a JSP+Servlet+Spring MVC application that is integrated within a parent application developed using Angular4 through an iframe. The issue arises when the Spring MVC app redirects to ...

Show method created by function, substituting the former element on the display

showButtons(1) will show radio buttons for frame number 1, showButtons(400) will display radio buttons for frame number 400. The current code shows all radio buttons for every frame up to 400 HOWEVER, I am aiming for a single set of radio buttons to start ...

Can you explain the step-by-step process of how an await/async program runs in TypeScript/JavaScript or Python?

As a C++ developer specializing in multithreading, I've been diving into the intricacies of async/await. It's been a challenge for me as these concepts differ from how C++ programs are typically executed. I grasp the concept of Promise objects, ...

Is there a way to append items to the main level of an array?

I am attempting to populate an array with objects in order to achieve the following structure: myobject1: Object: ItemInside: Object myobject2: Object ItemInside: Object myobject3: Object ItemInside: Object myobject4: Object ItemInside: Ob ...

Error encountered: Excelption - ENOENT - The specified file or directory does not exist: lstat node

I've been working on an Angular 12 application without any issues, but recently I encountered an error when trying to run it using ng serve. I've tried numerous solutions found on different websites, but nothing seems to work. I even went as far ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

While iterating through the material-ui rating component, the 'index' value remains constant at 0 within the 'onChange' function

For my e-commerce React.js web app, I want to show the rating value of each product. Using the JS map function, I was able to track which product was hovered by its index ('onChangeActive' is the handler for this). {products.map((product, index) ...

Adding to an existing array in SQLite by updating a column using Sequelize

My code includes a model definition for saving product data using Sequelize: This is how the Product model looks: import {Optional, Model, Sequelize, DataTypes } from 'sequelize'; /*This is the Product model used to save the data about products* ...

The program encountered an error: Unable to locate the module 'chart.js' in the directory '/node_modules/ng2-charts/fesm2015'

Having trouble with this error message: ERROR in ./node_modules/ng2-charts/fesm2015/ng2-charts.js Module not found: Error: Can't resolve 'chart.js' in /node_modules/ng2-charts/fesm2015' I ran the command "npm install --save ng2-chart ...

What is the best way to determine if a value from my array is present within a different object?

I have an array with oid and name data that I need to compare against an object to see if the oid value exists within it. Here is the array: const values = [ { "oid": "nbfwm6zz3d3s00", "name": "" ...

How is it possible for passing a number instead of a string to not result in a compilation error?

Here is some code that has caught my attention. It involves passing a number to a function that expects a string. const getGreeting: Function = (name: String): String => { return `hello, ${name}`; }; const x: number = 2 console.log(getGreeting(x)) ...

Ways to define an interface that can accommodate various interfaces with a specific structure

I am in need of a function that can accept a parameter with interfaces having a specific structure. The parameter should be either a string hash or a string hash along with an attribute string hash, as shown below: { anotherHash: { a: 'a', ...

What is the best way to ensure that a mapped type preserves its data types when accessing a variable?

I am currently working on preserving the types of an object that has string keys and values that can fall into two possible types. Consider this simple example: type Option1 = number type Option2 = string interface Options { readonly [key: string]: Op ...

Is it possible to prevent the Virtual Keyboard from automatically appearing on mobile devices?

Whenever a user enters a number on a page component, the Virtual Keyboard on their Mobile device pops up and shifts the entire page. I am looking for a solution to either disable the on-screen keyboard or ensure that the text box remains visible even when ...

Modify the MUI time picker to display as a digital clock inside a DateTimePicker widget

I need to update my MUI DateTimePicker component to use the DigitalClock time picker instead of the Analog Clock picker. The current component has two steps, first picking the date from a calendar and then selecting the time. This change is only necessary ...

Angular HTML fails to update correctly after changes in input data occur

Within my angular application, there is an asset creator component designed for creating, displaying, and editing THREE.js 3D models. The goal was to implement a tree-view list to showcase the nested groups of meshes that constitute the selected model, alo ...