简体   繁体   中英

Can you create object property names using template literals in javascript?

I'm attempting to write a function that takes an array of Strings as its input. The function should return an object with (1) key, value pair. The first element of the array should be the property name and the last element of the array should be its key.

function transformFirstAndLast(array){
    return {`${array[0]}`: array[length-1];}
}

The above gives me an error. Can someone provide a detailed explanation why this isn't working? I'd like to avoid creating separate variables to store the values from the first and last array indices.

You are missing the { and you can't use a template strings as a key. To use a "variable" as a key in an object, you should use the brakets around the variable. Here's the working code.

function transformFirstAndLast(array){
    return {[array[0]]: array[array.length-1]};
}

I guess template literal is unnecessary here simply try like this way after fixing this line array[length-1] because its wrong, correct one is array[array.length-1] . I've added more verbose code but you can also do the shorthand version like return {[array[0]]: array[array.length-1]}; on your transformFirstAndLast(array) function.

 function transformFirstAndLast(array){ const result = {}; result[array[0]] = array[array.length-1]; return result; } console.log(transformFirstAndLast(['a','b','c','d','e'])) 

yes you can use string literals as key. But the thing is that they are calculated in the run time. So you need to treat them as expressions. And to have variables/expressions as your keys you need to wrap them inside []

let a = {
  `key`: value
} // is not allowed

let a = {
  [`key`]: value
} // is allowed since you have wrapp

for your case

return {[`${array[0]}`]: array[array.length-1]};

Now since you have wrapped the array[0] item inside a string literal, you will get string values for your zero'th item. If your array[0] is to be a object this would not work as well. It needs to be either string or number. Or else you would get "[object Object]" as your key

Your question really boils down to, "Can I use expressions as keys in object literals?"

The answer is yes (since es6):

 function yell(template, ...parts) { return parts[0] + '!'; } function foo() { return 'bar'; } class Person { constructor(first, last) { this.first = first; this.last = last; } toString() { return `${this.first} ${this.last}`; } } let names = ['Abe']; let my_obj = { [3+5]: 'some_value', [yell `${foo()}`]: foo(), [names[0]]: 64, [new Person('Rafael', 'Cepeda')]: 25 }; console.log(my_obj); 

As long as the expression evaluates to a string, all is fair.

 var input = ["name", "fname", "lname", "stackOverflow"]; function transformFirstAndLast(array){ return {[array[0]]: array.pop()} } responseObject = transformFirstAndLast(input) console.log(responseObject) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM