Simple steps to duplicate an array in Typescript while also appending a new field to the duplicated array

I have an array of people. Each person object has fields for name and age. I want to create a new array by copying the original and adding a new field (country) to each person object. The country value will come from an array of strings. Therefore, the new objects in the array will have fields for name, age, and country. Check out my live example on Plunker here.

`export class App {
  index: number =0;
  countries: string [] = ['US', 'UK'];

  constructor() {
    this.persons = [
    {'name':'Marvin','age': 12}, 
    {'name':'Carla','age': 15}
    ];
    this.newPersons = this.persons.map(function(person){
      return {
        name:person.name,
        age : person.age
      }
    });
  }
}`

Answer №1

UPDATE:

We have discovered that there is no need for a separate array, but instead the 'country' field should be added to the existing persons array. This can easily be achieved using a simple for loop. In the loop, we will add a new property country to each object in the persons array, assigning the corresponding value from the countries array based on index:

for(let i=0;i<this.persons.length; i++) {
  this.persons[i].country = this.countries[i]
}

PLUNKER


PREVIOUS SOLUTION:

If you are looking to combine the two arrays and create objects with corresponding indexes, you can use the following code snippet:

// local variable to increment in map to get corresponding value of index in 'countries' array
i: number = 0;

this.newPersons = this.persons.map(a => Object.assign({name:a.name, age:a.age,country:this.countries[this.i++]}));

This will result in the output below:

[
  {
    "name": "Marvin",
    "age": 12,
    "country": "US"
  },
  {
    "name": "Carla",
    "age": 15,
    "country": "UK"
  }
]

Your PLUNKER

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

transfer information between different express middleware functions within a universal react application

I am working on an isomorphic react app and I am looking for a way to pass state between express middleware functions. One of my express routes handles form submission: export const createPaymentHandler = async (req: Request, res: Response, next: NextFun ...

A warning message has been triggered: 'Script Alert Error - Object

I've been putting in hours on a SUP project that requires some tweaking and I keep running into the issue Script Alert Error: Object expected The code I've added is: $('#bottomOfStart_ScreenForm').before('<div style="display: ...

Obtain the initial element in a table using pure Javascript

There are two tables presented in the following format: <table> <tr> <td></td> <td></td> </tr> </table> <table> <tr> <td></td> <td>&l ...

Shift all content to the right when viewing on mobile devices

I'm looking to create space for a menu on the left side, similar to the one on Mashable's mobile view. How can I move all the content to the right? Feel free to resize the window and compare with . Thank you. Best regards, Marius ...

Using Node.js to efficiently parse JSON data into customizable PUG templates

I have a challenge where I am parsing JSON data into elements called homeCards. To achieve this, I use Axios to request the JSON data and then utilize a for loop to cycle through it. Inside my Axios function, I extract the fields I need and store them in v ...

Using various props on multiple React components results in malfunction

I'm struggling with handling multiple instances of components even when using different key values for them. For instance, I have created 2 simple pages and passed different props to each. However, only one of them seems to log or alert properly. Shou ...

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Significant slowdown observed when deleting multiple objects from the Three.js scene

We are facing a challenge when dealing with large Three.js scenes that consist of many individual objects. In some cases, our scenes can contain anywhere from 25,000 to 50,000 instances of Object3D. While this may seem like a lot, we haven't found an ...

Utilizing Angular to Fetch JSON Data from a Server

I am currently retrieving data from a JSON file that resides on a server and is updated regularly. It's crucial for me to access this JSON content in order to consistently showcase the most recent information on my website. At present, I have stored ...

Is MongoDB-Stitch's Populate Method the best choice or are there comparable options available?

I am dealing with two collections, which I will refer to as A and B. Collection A contains documents that store the ObjectId of another document in collection B. For example: {name: String, age: String, bObjectId: ObjectId} When querying for an item in c ...

Tips for personalizing error messages for the "required" field by utilizing a dictionary feature on VeeValidate in Vue.Js

I am trying to update the error message that appears when an input field with the "cpf" rule is left empty (meaning it does not meet the "required" rule). I believe using the "dictionary method" with custom messages is the solution, but I am struggling to ...

Tricks for disabling _blank behavior in jquery?

I'm currently integrating a widget into a webpage using PHP. The widget contains jQuery code that causes all links to open in an external page. Is there a way to override or disable this code so it doesn't impact every link on the page? My prefe ...

How can I prevent Heroku from automatically running the script with 'npm start'?

I am currently in the process of developing a server-based application that utilizes automated scripts, also known as "bots," within a cloud environment. I have set up Heroku Scheduler to execute one of these scripts automatically, as illustrated in Figure ...

Thirteen consecutive attempts to fetch information have resulted in failure

I've encountered an issue while attempting to fetch data from my .NET Core 7 API. The error message I'm receiving is as follows: *Unhandled Runtime Error Error: fetch failed Call Stack Object.fetch node:internal/deps/undici/undici (11413:11) pro ...

Enhancing RTK Query: Efficiently Filtering Query Results in Separate Components

I am currently working on a Todo application using Nextjs 13 with various tools such as app directory, prisma, redux toolkit, shadcnui, and clerk. Within my app, I have implemented two key components - TodoList and Filter. The TodoList component is respons ...

"An error occurred stating that _co.JSON is not defined in

During my attempt to convert an object into a string using the JSON method, I encountered an error upon loading my page: Error: _co.JSON is undefined The stacktrace for this error message is extensive and seems unnecessary to include at this point. Th ...

Limit search to retrieve specific items based on pointer in JavaScript using Parse.com

BlogApp.Collections.Blogs = Parse.Collection.extend({ model: BlogApp.Models.Blog, query: (new Parse.Query(BlogApp.Models.Blog)).equalTo("author", "xMQR0A1Us6").descending('createdAt').limit(9) }); The code snippet above doesn't seem ...

Searching for values in JSON using jQuery's autocomplete feature

I have implemented jquery autocomplete with a json request in my code. Here is the code snippet for the autocomplete feature: $("#company_name").autocomplete({ source: function( request, response ) { $.ajax({ url: "https://ur ...

Adding a detached <li> element to a <ul> list: step-by

I am currently facing an issue with adding a li element after deleting it from a ul list. I have experimented with various methods using append() and appendTo() but to no avail. https://jsfiddle.net/kq1yyoLk/ The main concept is that when you click on ite ...

Controlling an AJAX request to fetch individuals

I am currently using an ajax request to display people data on the page, which is retrieved from a backend database. The search form on the page includes options for location, sector, service, and job title. Below is the javascript code being used: //var ...