1

I have an array of strings array ['one','two',three'] and would like to transform this into a key value pair so that it looks like (first element is the key and last element the value):

{
  one:'three'
}

This is how far I've gotten:

function t(array) {
var key = array[0];
return {key:array[array.length-1]}
}

output:

{ key: 'three' }

The value is correct but the key is not displaying correctly.

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
magicsword
  • 1,179
  • 3
  • 16
  • 26

2 Answers2

8

You need square bracket around key to evaluate its content as the key of the object:

var arr = ['one', 'two', 'three'];

function t(array) {
  var key = array[0];
  return { [key]:array[array.length-1] }
}

console.log(t(arr))
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

Use square bracket while accessing properties using variables

var array = ['one', 'two', 'three ']

function t(array) {
  var key = array[0];
  var obj = {};
  obj[key] = array[array.length - 1]
  return obj;
}
console.log(t(array))
brk
  • 48,835
  • 10
  • 56
  • 78