magicsword magicsword - 3 years ago 158
Javascript Question

Key Value Pairs in JavaScript

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.

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

console.log(t(arr))

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