Reputation: 315
I am trying to create a function that returns a new object with a key–value pair. I am getting the key and value from the first and last elements of an array. I can get the function to return the elements that will make up the key–value pair, but as soon as I wrap the array elements in curly braces to return an object via the function, it doesn’t work. What is the problem?
// Create an array
var names = ["Apples", "Oranges", "Yummy", "Candy", "Plop"];
// Return an object with a key–value pair from the first and last element of an array
function firstLast(array) {
var obj = {
array[0] + ": " + "'" + array[array.length - 1] + "'";
};
return obj;
}
console.log(firstLast(names));
Upvotes: 0
Views: 45
Reputation: 15499
You can use square brackets notation to assign the value, but my initial post contained the same answer as @Xufox's alternative. So I thought I would present a different approach that uses the arguments that are passed into the function and build the returned object from shifting and popping from that array. Just a different wy of doing the same job.
var names = ["Apples", "Oranges", "Yummy", "Candy", "Plop"];
function firstLast(array) {
return {[arguments[0].shift()]: arguments[0].pop()};
}
console.log(firstLast(names));
Upvotes: 1
Reputation: 19475
That’s invalid syntax. What you need is this:
var obj = {
[array[0]]: array[array.length - 1]
};
This uses computed properties.
An alternative would be:
var obj = {};
obj[array[0]] = array[array.length - 1];
Upvotes: 4