A guide to dynamically updating key values in an array of objects using Typescript

Within my array called objectArray, I have an object with keys representing different types of clothes.

const objectArray: clothesTypes[] = [
  {
    trousers: 90,
   'skirts and jackets': 47,
    scarfs: 100,
  },
]

I also have another array named userArray[], which keeps track of user data when purchasing clothes.

const userArray: userData[] = [
  {
    name: 'David',
    clothType: 'trousers',
    price: 45,
  },
  {
    name: 'Joanna',
    clothType: 'scarfs',
    price: 5,
  },
  {
    name: 'Gillian',
    clothType: 'trousers',
    price: 35,
  },
]

The task at hand is to update the values of the keys in the objectArray based on the number of objects with corresponding 'clothType' in the userArray. For instance, trousers should have a value of 2, 'skirts and jackets' should be 0, and scarfs should be 1.


This is my attempted method:

objectArray.map(item => ({
  ...item,
  ...{
    trousers: userArray.filter(d => d.clothType === 'trousers').length,
    'skirts and jackets': userArray.filter(d => d.clothType === 'skirts and jackets').length,
    scarfs: userArray.filter(d => d.clothType === 'scarfs').length,
  },
})),

Is there a way to achieve this without manually assigning values to each key?

Thank you!

Answer №1

The inquiry's creator noted that the objectArray consists of an array with a fixed length of 1. In light of this information, here is my proposed solution -

Reiterating what was mentioned in a prior comment, there isn't a method to execute this all "at once"; one would need to iterate and tally, however, it's feasible to enhance the algorithm slightly (notably if the objectArray doesn't have to be an array due to its consistent length of one)

Access the complete functioning example on TypeScript Playground

const userArray: userData[] = [
  {
    name: 'David',
    clothType: 'trousers',
    price: 45,
  },
  {
    name: 'Joanna',
    clothType: 'scarfs',
    price: 5,
  },
  {
    name: 'Gillian',
    clothType: 'trousers',
    price: 35,
  },
]

const clothesCount: clothesTypes = {
    trousers: 90,
    'skirts and jackets': 47,
    scarfs: 100,
}

userArray.reduce((pv, cv) => {
  switch(cv.clothType) {
    case 'scarfs':
      pv['scarfs'] += 1;
      break;
    case 'skirts and jackets':
      pv['skirts and jackets'] += 1;
      break;
    case 'trousers': 
      pv['trousers'] += 1;
      break;
  }
  return pv;
}, clothesCount)

Answer №2

To determine the count of properties that exist in both `userArray` and `objectArray`, you can loop through `userArray` and check if the property exists in `objectArray`.

const objectArray: clothesTypes[] = [{
  trousers: 90,
  'skirts and jackets': 47,
  scarfs: 100,
}, ];

const userArray: userData[] = [{
    name: 'David',
    clothType: 'trousers',
    price: 45,
  },
  {
    name: 'Joanna',
    clothType: 'scarfs',
    price: 5,
  },
  {
    name: 'Gillian',
    clothType: 'trousers',
    price: 35,
  },
];

const objectArrayClone = [...objectArray];
const objectArrayV = objectArrayClone[0];
userArray.forEach((obj) => {
    const { clothType } = obj;
    if (clothType in objectArrayV) {
        objectArrayV[clothType]++;
    }
});

console.log(objectArrayClone);

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

ERROR Error: Uncaught (in promise): ContradictionError: The variable this.products is being incorrectly identified as non-iterable, although it

Seeking a way to extract unique values from a JSON array. The data is fetched through the fetch API, which can be iterated through easily. [please note that the product variable contains sample JSON data, I actually populate it by calling GetAllProducts( ...

TypeScript will show an error message if it attempts to return a value and instead throws an

Here is the function in question: public getObject(obj:IObjectsCommonJSON): ObjectsCommon { const id = obj.id; this.objectCollector.forEach( object => { if(object.getID() === id){ return object; } }); throw new Erro ...

`How can create-react-app with typescript be set up to automatically utilize ts-loader for node modules written in typescript?`

Currently, I am working on a project named client which relies on components and services from the core project. The core project, written in TypeScript, has not been compiled or built yet. To speed up the development of the client application, I need to w ...

Setting default parameters for TypeScript generics

Let's say I define a function like this: const myFunc = <T, > (data: T) => { return data?.map((d) => ({name: d.name}) } The TypeScript compiler throws an error saying: Property 'name' does not exist on type 'T', whic ...

Can the WebSocket interface be substituted with WebSocket itself?

I'm currently in the process of setting up a WebSocket.Server using ws, Express 4, NodeJS, and TypeScript by following a guide. However, I've encountered an issue with the provided code not working as expected from the tutorial found at . In ord ...

Despite setting the esModuleInterop flag, I am still encountering an error with default imports

My React project with TypeScript is causing some issues. In the main tsx file, the import React from 'react' line works fine. However, in my test file, I keep getting the TS1259 error. I suspect there might be a problem with my TS/Jest/Babel conf ...

Is there a way to stop observing an Observable or Subject after its first emission while setting up the observer?

Currently, I am in the process of implementing dialogs using Angular 9 and I encountered a scenario where I need to unsubscribe from a Subject after its first emission. Initially, my approach was to use the take(1) or first() operators to transform the Su ...

Guide on utilizing the useContext hook in React/Next.js while incorporating TypeScript

As I embark on my journey in the world of TypeScript, I find myself working on a new project in Next.js using TypeScript. My goal is to incorporate authentication functionality into this project by utilizing createContext. Coming from a background in JavaS ...

Error in Angular 5: Attempting to access 'subscribe' property of undefined variable

I've been struggling for days trying to fix this error on Stack Overflow. Since I'm new to Angular, I decided to reach out to the community for help. The issue revolves around JWT authentication. ERROR TypeError: Cannot read property 'sub ...

Verify registration by sending an email to an alternate email address through Angular Firebase

I have implemented email verification for users before registration. However, I would like to receive a verification email to my own email address in order to finalize the registration process. I want to be notified via email and only after my approval sho ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...

Angular 2 Form Error: Control Not Found

I'm facing an issue with Angular 2 Forms where adding more than one control seems to be getting ignored. Despite following numerous guides on how to properly implement this, none of the suggested methods seem to work in my case. In my template, I hav ...

"Encountering a 'Module Not Found' error in Node.js after

Recently, I added a node-module to my project using the command: npm install typescript --save-dev However, when I tried running: tsc Windows displayed an error message indicating that "tsc" is an unknown command. Strangely, this issue does not occur o ...

What is the best way to showcase a view on the same page after clicking on a link/button in Angular?

Is there a way to show a view on the same page in an Angular application when a link is clicked? Rather than opening a new page, I want it displayed alongside the list component. How can this be accomplished? Here's an illustration of my goal: I&apos ...

Jhipster: Allowing users to effortlessly generate linked objects under their account

My goal is to develop a service that assists individuals in making informed decisions. To achieve this, I must guide users through an onboarding process where they create entities that reflect their circumstances. During data input, I aim to establish lin ...

Utilizing type maps within nested objects in Typescript: A comprehensive guide

Initially, a type is established that connects enum keys with specific types: enum MyEnum { A, B } type TypeMap = { [MyEnum.A]:string, [MyEnum.B]:number } interface ObjInterface<T extends keyof TypeMap> { obj: T, objData: Ty ...

Unable to utilize AgmMarkerSpiderModule

I followed the instructions to add the AgmMarkerSpiderModule from the official package documentation. However, when I compile, I encountered the following error message: /directives/marker-spider.ts:14:24 - error TS2307: Cannot find module '@agm/core/ ...

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

Removing a field from a collection using firebase-admin: Tips and tricks

I currently have a collection stored in Firebase Realtime Database structured like this: https://i.sstatic.net/jNiaO.png My requirement is to remove the first element (the one ending with Wt6J) from the database using firebase-admin. Below is the code s ...

Create a number line dynamically with Typescript

I am currently working on a project where users can create sales. Within each sale, users are able to add multiple products which are stored in an array and then submitted to a table. I need each product row in the table to have a unique ID known as "line_ ...