JSON Object Key passed as a parameter in a function

While I have seen a similar question before, I am still unsure how to apply the solution in my specific case.

I am working with a function that returns a stringified JSON object, but I need to modify one of the keys using a parameter within the function. Here is an attempt I made to replace it with the parameter value:

function toJSON(... name: string, timestamp: number, x :number, y: number ...): string {
    return JSON.stringify({

         ...

        `${name}`: [
          {
            timestamp: timestamp,
            x: x,
            y: y
          }
        ]
        
        ...

    })

Is there a straightforward way to simply substitute this key with a parameter?

In this context, the ... serves as a placeholder for additional content both before and after.

Answer №1

Great job! Consider implementing computed property using the new notations introduced in ECMAScript 2015, as detailed in this resource:

function toJSON(...props: string, timestamp: number, x:number, y: number ...): string {
  return JSON.stringify({
    ...,
    [props]: [{ timestamp, x, y }]
  });
};

With ES2015, you have the option to use shorthand property names for a more concise syntax, like { timestamp, x, y } instead of repetitive

{ timestamp: timestamp, x: x, y: y }

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

Choosing the default option (India) in AngularJS is a simple process

My project involves displaying a list of country names in a select box, with the options coming from an external JSON file. Once a country is selected, I load another JSON file containing states for that country into a separate select box. Everything was w ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

What is the significance of the IRenderFunction interface definition in FluentUI?

Recently diving into TypeScript, I've begun working with DetailsList in Fluent UI. Check it out here: https://developer.microsoft.com/en-us/fluentui#/controls/web/detailslist. I'm exploring the onRenderRow property, which is of type IRenderFunct ...

Troubleshooting Problems with Loading Data into Highcharts using Javascript

The server is returning data in the following format: {"barData": [ {"Accepted":[0,0,0]}, {"Rejected":[0,0,0]}, {"In_Process":[0,1,0]}] } On the browser, it appears as follows: I initially thought that this was the correct st ...

The Telegram response to the InlineQuery is unable to interpret the numerical value

I have been developing a bot with a new feature of the Telegram bot API called InlineQuery. I have implemented all types in C# and am now able to receive queries returned from Telegram to my bot. However, when I try to answer the query by posting the follo ...

Implementing modifications to a current service in Kubernetes using a JSON file

Can someone assist me in updating my SVC configuration by using a JSON file? My current SVC is running as a ClusterIP, but I would like to change it to an Ingress kind with the type of load balancer. Here is the current service information: kubectl -n nifi ...

ERROR: The use of @xenova/transformers for importing requires ESM

When working with my Node.js application, I usually start by importing the necessary modules like this: import { AutoModel, AutoTokenizer } from '@xenova/transformers'; Afterwards, I utilize them in my code as shown below: const tokenizer = awai ...

Exploring genres on iTunes through a search function

(I have modified the code to remove C# snippets that were not helpful and now I hope the issue is clearer) I am attempting to retrieve a list of podcasts by genre from iTunes using the API outlined in to the best of my ability. I can easily search for a ...

Execute a query to retrieve a list of names and convert it to JSON using Unicode encoding in

Just starting out with Laravel and I'm trying to figure out how to execute some queries Not talking about the usual select statements... I need to run this specific query: SET NAMES 'utf8' First question, here we go: I have Hebrew ...

Developing hierarchical JSON objects with PHP and MySQL

Suppose I've successfully created two tables within my database: `INSERT INTO `months` (`month_id`, `month_name`) VALUES ('1', 'January');` and `INSERT INTO `weeks_and_days` (`week_id`, `week_nr`, `day_nr`) VALUES ('1&apos ...

Displaying a single http response in Angular

Having trouble displaying data from a single JSON response using Angular. I've set up a class for the data in interndata.model.ts export class Interndata { humidity: number; temperature: number; constructor(humidity:number, temperature:number) { ...

C++ code for finding, replacing, and appending strings

I am faced with the task of using getline(infile, aSentence) on 4 different sentences within a file and saving them as strings. Subsequently, I need to devise an algorithm that shifts every word's first letter to the end and appends "ay" to it. For i ...

Is there a way to revert my Ionic CLI back to the previous version that I had installed?

Having just updated to version 3.2.0, I am encountering numerous issues, such as the malfunctioning of the ionic serve command. ...

Leveraging NPM workspaces in combination with Expo and Typescript

I'm struggling to incorporate NPM 7 workspaces into a Typescript Expo project. The goal is to maintain the standard Expo structure, with the root App.tsx file, while segregating certain code sections into workspaces. I'm facing challenges compil ...

Oops! The formGroup function in Angular 5 requires an instance of a FormGroup

While working with Angular 5, I encountered an error in this basic form. Here is the issue: Error Message: EditVisitanteDialogComponent.html:10 ERROR Error: formGroup expects a FormGroup instance. Please pass one in. Example: > > &l ...

Step-by-step guide on implementing virtual scroll feature with ngFor Directive in Ionic 2

I am working on a project where I need to repeat a card multiple times using ngFor. Since the number of cards will vary each time the page loads, I want to use virtual scrolling to handle any potential overflow. However, I have been struggling to get it ...

Changing a JSON object into a collection of string arrays using jq

I have a JSON object that consists of strings and nested objects: { "key1": "value1", "key2": "value2", "key3": { "subKey1":"value3", "subKey2":"value4" } } My goal is to flatten the structure and convert it into an array of strings [ ...

Execute the unknown function parameter

Trying to figure out how to convert an argument into an anonymous function, but struggling to find clear instructions. I know how to cast on variable assignment, but unsure if it's possible and how. Working with lodash where the typings specify the a ...

Challenge: iPhone interacting with a Drupal website through a JSON RPC Server

I'm struggling to figure out how to send a JSON RPC request using Obj-C. Can anyone lend me a hand? Here is what I have attempted so far: responseData = [[NSMutableData data] retain]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL ...

Angular: Identifier for Dropdown with Multiple Selection

I have recently set up a multi select dropdown with checkboxes by following the instructions provided in this post: https://github.com/NileshPatel17/ng-multiselect-dropdown This is how I implemented it: <div (mouseleave)="showDropDown = false" [class. ...