Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Key of JSON Object as from function parameter

I know this question was already here, but I do not know how to use it in my case.

I have a function which returns a stringified JSON but I need to change one key with a parameter of this function. I tried something like this to replace it with the value:

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

         ...

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

    })

Is there an easy way to just replace this Key with a parameter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the ... means more stuff before and after

>Solution :

Almost good, you should use computed property https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015 instead of string template:

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

Since es2015, you can use shorthand property names, so you can write { timestamp, x, y } instead of redundand: { timestamp: timestamp, x: x, y: y }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading