2

I have to stringify some parameter to put it in a http patch request my method is something like this

let param = JSON.stringify({
code : this.code,
name : this.name,
fieldName: this.data
});

In that case I have a param like this:

code:3,name:'asdf',fieldName: 'col'

But I want the value of fieldName ond not the word fieldName... Is there a method to expand or evaluate this parameter name?

1 Answer 1

5

If you want value of code variable to be used as a key name, then you need to use computed object property notation:

let param = JSON.stringify({
  [code]: this.code,
  [name]: this.name,
  [fieldName]: this.data
});

In the old days we would have to create object separately and assign variable keys in separate step using bracket notation:

let params = {}
params[code] = this.code
params[name] = this.name
params[fieldName] = this.data

let param = JSON.strigify(params)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I have another issue, maybe i'll open a new question...How can I prevent json stringify to convert Date? Apr 18 2017 00:00:00 GMT+0200 is stringified to: 2017-04-17T22:00:00.000Z
Date will need to be represented somehow if you stringify it. You can always redefine toJSON method of date object to return whatever you need. const d = new Date; d.toJSON = () => 'Hello'; ....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.