Adjust the key values within an array of objects in TypeScript

I am looking to update the keys' values of the 1st object within an array of objects.

Here is what I have attempted so far:

The array of objects:

const objArray: FoodItems[] = [
  {
    apple: 4,
    banana: 7,
    'mango & grapes': 9,
    Cherry: 7,
  },
]

The type of the above object is FooItems[]:

export type FoodItems = {
  apple: number;
  banana: number;
  'mango & grapes': number;
  Cherry: number;
}

The new value that needs to be assigned to the key:

const newValue = 34;

The code snippet I used to attempt modifying each key:

objArray.map(item => ({
  ...item,
  ...{
    apple: newValue,
    banana: newValue,
    'mango & grapes': newValue,
    Cherry: newValue,
  },
})),

Is there a more efficient way to achieve this task, rather than updating each key individually?

Thanks in advance...

Answer №1

One approach is to convert the keys of the current object into an array of entries in order to build a new object with a designated newValue as the value.

const objArray = [
  {
    apple: 4,
    banana: 7,
    'mango & grapes': 9,
    Cherry: 7,
  },
];
const newValue = 34;
const newArray = objArray.map(item => Object.fromEntries(
  Object.keys(item)
    .map(key => [key, newValue])
));
console.log(newArray);

If you want the resulting type to be an array named FoodItems - TypeScript is most effective with static keys. It may seem odd to apply the same operation to all keys of an object to create a new one, but that's the task at hand. The simplest way to achieve this would be to assert that the type of the Object.fromEntries result matches the desired type:

const newArray = objArray.map(item => Object.fromEntries(
  Object.keys(item)
    .map(key => [key, newValue])
) as FoodItems);

Subsequently, newArray will be equivalent to FoodItems[].

Regrettably, Object.keys and similar methods do not return the keyof the object - only a type of string - so you either need to assert the type of the outcome (as illustrated above) or explicitly declare each individual property (as originally intended).

Answer №2

When merging objects, the properties in the target object will be replaced by those in the sources if they share the same key. The properties from later sources take precedence over earlier ones.

Learn more about Object.assign here

const objArray = [
  {
    apple: 4,
    banana: 7,
    'mango & grapes': 9,
    Cherry: 7,
  },
]

const newObj = {
    apple: 1,
    banana: 2,
    'mango & grapes': 3,
    Cherry: 4,
  }
  
  newObjArray = objArray.map(item => Object.assign(item, newObj))
  console.log(newObjArray)

Answer №3

By looping through the keys of each object, we can update their values without modifying the object reference or creating a new object.

const objArray = [
  {
    apple: 4,
    banana: 7,
    'mango & grapes': 9,
    Cherry: 7,
  },
]

const newValue = 34;
  
newObjArray = objArray.forEach(item => Object.keys(item)
  .forEach(key => item[key] = newValue))
console.log(objArray)

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

Using object in Typescript for function overloading - External visibility of implementation signatures for overloads is restricted

Issue How do I correctly expose an overloaded implementation signature? Scenario Expanding on the initial query: interface MyMap<T> { [id: string]: T; } type Options = { asObject?: boolean, other?: Function testing?: number }; function g ...

What sets React.FC<T> apart from Function() in TypeScript?

Do arrow functions and function notations differ from each other? It seems like these two methods function in the same way. One is written as React.FC<T> while the other as Function(). Is this simply a matter of notation, or are there deeper reaso ...

Extend an array by Parsing JSON

I'm struggling to retrieve the JSON string from localStorage and add a new dish to it. It's not functioning correctly, can anyone lend me a hand? I am utilizing TypeScript. interface Dish { id: number; name: string; desc: string; ...

Error encountered: The term 'interface' is a restricted keyword

I am in the process of developing a NodeJS and MongoDB library for performing CRUD operations on APIs. My goal is to establish an interface with Typescript that includes the url and database name, structured as follows: However, I am encountering this par ...

After the click event, the variable in the Angular .ts file does not get refreshed

Great! I have a service in my .ts component that loops through an array of court names. Every time I click on a next or back arrow event, a counter is incremented starting at 0, where index 0 corresponds to field 1 and so on. The issue I'm facing is ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

Issue with Angular: ngForm object does not capture selected option

Revise to clean up unnecessary code. Having trouble displaying the selected option when I print the form object to the console. It's showing as undefined. Any guidance on what might be wrong with this code would be appreciated. Let me know if more in ...

JavaScript - Trouble encountered while trying to use splice to insert one array into another array

I've been working on creating a Cache Hashtable using JavaScript. When I use the code cache.splice(0,0, ...dataPage);, it inserts my data starting from the first position up to the length of dataPage. Assuming that my dataPage size is always 10. Th ...

ReactJS Error: The property 'hubConnection' is not defined on type 'JQueryStatic'

I am currently working with the Signalr library in React, but I keep encountering the following error: Property 'hubConnection' does not exist on type 'JQueryStatic'. Is there a solution to this issue? declare var window : any; import ...

Angular Pause until the variable is ready

I am in the process of developing a new web application service. The first step involves obtaining a token through the rest API. Once this token is obtained, it needs to be sent as a header to retrieve additional information. The issue I'm facing is ...

Problem with extending a legacy JavaScript library using TypeScript

Can someone assist me with importing files? I am currently utilizing @types/leaflet which defines a specific type. export namespace Icon { interface DefaultIconOptions extends BaseIconOptions { imagePath?: string; } class Default exte ...

Create a class with additional attributes to support different types of options

I define a set of options represented by strings: export type Category = 'people' | 'projects' | 'topics' | 'tools' An index is declared as follows: interface Entry { ... } type IPostEntryIndex = { [name in Cate ...

Attempting to categorize JSON object elements into separate arrays dynamically depending on their values

Here's the JSON data I'm currently working with: ?$where=camis%20=%2230112340%22 I plan to dynamically generate queries using different datasets, so the information will vary. My main objective is to categorize elements within this array into ...

I'm curious about why the value of my variable in service.ts keeps changing whenever the page is refreshed?

Below is my Angular service.ts file code. It is used to store the login status. import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) e ...

When attempting to access a static method in TypeScript, an error occurs indicating that the property 'users_index' does not exist on the type 'typeof UserApiController'

Just dipping my toes into TypeScript and attempting to invoke a function on a class. In file A: import userAPIController from "./controllers/customer/userAPIController"; userAPIController.users_index(); In file B: export default class UserApiControlle ...

Transform the process.env into <any> type using TypeScript

Need help with handling logging statements: log.info('docker.r2g run routine is waiting for exit signal from the user. The container id is:', chalk.bold(process.env.r2g_container_id)); log.info('to inspect the container, use:', chalk.b ...

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...

The editor is locked and choices are displayed in a vertical orientation

I'm currently experimenting with using draft js in my project to create a wysiwyg editor. However, I've encountered an issue where the editor appears vertically instead of horizontally when I load the component. Any idea why this might be happen ...

The interface 'Response<ResBody>' has been incorrectly extended by the interface 'Response'

I am currently working with typescript and express in a node.js environment. Whenever I compile my code, I encounter the following bug: node_modules/@types/express-serve-static-core/index.d.ts:505:18 - error TS2430: Interface 'Response<ResBody>& ...

Can you showcase two distinct perspectives on a single page?

One of my components has nested ngFor directives looping through an array of users and their posts. I have a view link within this element, and when clicked, it should show detailed information about both the user and the post. However, the current setup i ...