Home > database >  Key of JSON Object as from function parameter
Key of JSON Object as from function parameter

Time:03-02

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?

the ... means more stuff before and after

CodePudding user response:

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 }

  • Related