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

What is this strange javascript object syntax?

this is a strange question for a strange syntax I’ve found and I can’t explain the reason why one would use it:

let ranges = [];

// field and value are simple strings
for (const [field, value] of Object.entries(this.$route.query)){ 
  ranges.push({ [field] : value });
}

Now, that [field] makes quite no sense to me. Why would one use that ‘array’ syntax? Also, I thought it wasn’t even possible to assign an array as an object key. And also, if I log the resulting object, I can see that [field] in fact is converted to "field", in other words, just like writing

ranges.push({ field : value });

Am I missing something or the { [field] : value } is quite useless?

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

>Solution :

This is an example:

the use of { [field]: value } is not useless, it allows you to dynamically set the key of the object based on the value of the field variable.

let field = 'example';
let value = 50

// Using computed property names
let obj1 = { [field]: value };
console.log(obj1); // Output: { example: 50 }

// Without computed property names
let obj2 = { field: value };
console.log(obj2); // Output: { field: 50 }
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