magicsword magicsword - 3 years ago 158
Javascript Question

Key Value Pairs in JavaScript

I have an array of strings array

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):


This is how far I've gotten:

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


{ key: 'three' }

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

Answer Source

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


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download