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?
>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 }