4

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.

1
  • The first element of the array should be the property name and the last element of the array should be its key or value? Commented Oct 17, 2018 at 0:48

5 Answers 5

3

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.

1

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]};
}
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']))

1

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

0

var input = ["name", "fname", "lname", "stackOverflow"];

function transformFirstAndLast(array){
    return {[array[0]]: array.pop()}
}

responseObject = transformFirstAndLast(input)
console.log(responseObject)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.