Adding a Key Value pair to every object within an Array using TypeScript

I have two arrays - one contains dates and the other contains objects. My goal is to include the dates as a key value pair in each object, like this: {"Date": "10-12-18"}.

dates:

["10-12-18", "10-13-18", 10-14-18"]

data:

[
   {"name":"One", "age": "4"},
   {"name":"Two", "age": "5"},
   {"name":"Three", "age": "9"}
]

I envision my final data structure to look something like this...

[
    {"name":"One", "age": "4", "Date": "10-12-18"},
    ....

I am struggling with TypeScript so far as I am more accustomed to regular JavaScript. Here's what I've attempted:

for (let idx of data){
   data[idx].date = dates[idx] 
}

Any tips on how to solve this would be greatly appreciated!

Answer №1

Your code has an issue where `idx` refers to the object instead of the index due to the use of `for...of` loop. You should switch to a basic `for` loop like this:

for(let idx = 0; idx < data.length; idx++) {
    data[idx].date = dates[idx];
}

Alternatively, you can utilize `forEach` method to iterate through one array and access values from another array using the provided index:

data.forEach((obj, i) => obj.date = dates[i]);

Answer №2

const updatedData = data.map(({ name, age }, index) => ({ name, age, date: dates[index] }));

Transform the array into a new format with the desired result.

Answer №3

Here is a similar example:


    let colors = ["blue", "green", "red"];

    let items = [{"type":"car",
     "brand": "Toyota"},

     {"type":"bike",
     "brand": "Honda"},

    {"type":"truck",
     "brand": "Ford"}
    ]

    const updatedItems = items.map((object, idx) => {
        object.Color = colors[idx];
        return object;
    });

console.log(updatedItems);

Answer №4

As mentioned by @Sarah Smith, I strongly believe that utilizing the map operator is the most effective approach.

An alternative method is to employ the spread operator instead of object destructuring, demonstrated below:

const items = [
   { 'name':'Apple', 'quantity': '10' },
   { 'name':'Banana', 'quantity': '5' },
   { 'name':'Orange', 'quantity': '8' }
];

const prices = ['$2', '$3', '$1'];

const output = items.map((item, i) => ({ ...item, price: prices[i] }));

This technique proves particularly useful when dealing with complex objects as it eliminates the need to manually rewrite each key.

Answer №5

Here is how you can achieve this in TypeScript:

const info = [{
    "name": "John",
    "age": "25"
  },

  {
    "name": "Sarah",
    "age": "32"
  },

  {
    "name": "Mike",
    "age": "45"
  }
];

const dates = ["10-12-21", "10-13-21", "10-14-21"];

console.log(info.map((item, index) => ({ ...item,
  "Date": dates[index]
})));

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

Combining similar validators in VueJS into one group

Upon installation of the vuelidate.js.org package for VueJs, I implemented the following validator script: }), Validations: { name: { required, minLength: minLength(3), maxLength: maxLength(50) }, family: { required, minLength: ...

Visualization of pie charts in Angular2 using Google library

Currently, I am in the process of building a web application using Angular2 that includes a Google pie chart. One of the components of the application is a Directive specifically designed for the pie chart. Below is the code snippet for the Directive: @D ...

Showing the Enum name rather than the value in an Angular HTML template for a bound Typescript Interface

After retrieving an array of objects with various properties from a .NET Controller, I am utilizing the following Typescript code: import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Co ...

Tips for implementing an automated date picker in Selenium using Node.js

I attempted to automate a date picker like the one shown in this screenshot: https://i.sstatic.net/GtJ22.png Below is the code I used to automate it using Selenium with NodeJS: const { By, Key, Builder, WebElement, Alert } = require('selenium-webd ...

Sending an array with a specific identifier through JQuery ajax

I'm facing an issue where I am sending an array of values via jQuery AJAX to my servlet. However, the servlet is only picking up the first value in the array, even though there are more elements present. $.ajax({ type: "POST", url: "mySer ...

How can we add styles to text entered into a form input field in a targeted way?

Is there a way to apply styling to the second word entered into a form input text field after the user hits "enter" and the data is output? In this scenario, the text always follows the format of 3 numbers, followed by a space, and then a name. For examp ...

What is the best practice for adding a DOM element at a precise location within an ng-repeat loop?

I am currently working on developing a podcast player application using AngularJS. At this point, I have successfully created a list of available podcasts that can be played, utilizing ng-repeat. The code for the list is shown below: <ul ng-controller ...

What are the steps for utilizing the Object.entries(...) method along with .forEach and .every

Using a constant queryModifier = {price: "lessThan", weight: "greaterThan"}, I am filtering a list. const queryKeys = keys: { price: '1000', weight: '1000' } const list = [ { // object data here }, { // o ...

What is the method to modify an action in an Ajax function?

I am trying to modify the action in the AjaxUpload function. The issue is that the value of setnamefile in the action does not change because the page does not reload. My idea was to change the action on submit, but I have not been able to do so successfu ...

Is the PHP Ajax parameter missing during the upload process?

I'm attempting to do a simple upload, but I seem to be struggling. It could be that I'm not understanding it properly, or perhaps it's just too late at night for me to figure it out. After doing some research, I came across this example on ...

Is it possible for the data submitted in a POST request to be converted into URL parameters?

Our technology stack: Frontend built with Vue.js and utilizing the vuetify component library Custom Python middleware REST API using Flask + Tornado External Matomo setup connected to the frontend via the vue-matomo plugin system (https://github.com/Amaz ...

It's next to impossible to secure expedited work on an ongoing project using Vercel

Yesterday, I successfully deployed an application on Vercel using only ReactJS. Today, I made the decision to develop an API for my application, To clarify, I have a folder housing the React app, and within that, I created a directory named "api" followi ...

My presentations are not functioning as expected, could there be a problem with my HTML, CSS, or JavaScript coding?

My website utilizes a Slideshow feature to display images for blog posts. Recently, I attempted to include multiple slideshows within an article, which unfortunately caused all of the slideshows to malfunction. As it stands now, when the code is executed, ...

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

My HTML file is not able to load my Javascript file

I'm currently working on integrating a JavaScript code for a show more and show less feature on my page. The goal is to limit the description so that it shows only a certain number of characters, with an option to expand or collapse the text. However, ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

Exploring the capabilities of the Angular 2 expression parser alongside the functionality of the

Is there a way to create an equivalent of the Angular 1.x ngInit directive in Angular 2? I am familiar with the ngOnInit hook, which is recommended for initialization code. The ngInit directive seems like a quick and declarative way to prototype or fix a ...

What is the reason behind the android code being incompatible with IOS operating systems?

I'm encountering an issue where a particular code is working on Android, but not on IOS. The code in question involves using JavaScript to differentiate the items in a list within an HTML select tag. It's perplexing to me how the code can operat ...

Transform a text node into an HTML element with the help of JQuery

Consider this HTML snippet: <div> Lorem ipsum <span>dolor sit</span> amet <span>consectetur adipiscing elit</span> eiusmod tempor </div> To select the text nodes [Lorem ipsum, amet, eiusmod tempor], ...

What could be causing the sluggish performance of my JavaScript code?

Could someone offer insight into why my JavaScript code is performing slowly? Are there any optimizations I can implement to improve its speed? Thank you! $(document).ready(function() { /* Trigger animation when window is scrolled */ $(window).scroll( ...