Advokaten01
Advokaten01

Reputation: 65

Can't create JS object with array indices as key & value?

Task: convert an array into an object with one key-value pair, where the first array item is the key, and the last array item is the value.

E.g., [1,2,3] should convert to {1: 3}

I can't get it to work as:

function transformFirstAndLast(array) {
  var firstLast = {
    array[0]: array[-1]
  };
  return firstLast
}

But only as:

function transformFirstAndLast(array) {
  var firstLast = {};
  firstLast[array[0]] = array[array.length - 1];
  return firstLast
}

...why doesn't the first work? Why can't you index the array for the key & value?

Upvotes: 2

Views: 678

Answers (3)

Scott Marcus
Scott Marcus

Reputation: 65806

First, you must remember than an array is a type of JavaScript object and, in JavaScript, an object property (a.k.a. "key") can be accessed or assigned in two ways:

via "dot notation"

object.property = value;

via array syntax

object["property"] = value;

Next, remember that, in JavaScript, if you assign a value to a property that doesn't exist (using either syntax from above), the property will be created, like in the following:

console.log(window.someNewProperty);         // undefined
window.someNewProperty = 17;                 // This causes the property to be created
window["someOtherNewProperty"] = "Voilla!";  // So does this, just with array syntax
console.log(window.someNewProperty);         // 17
console.log(window["someOtherNewProperty"]); // "Voilla!"

Now, moving on to the specifics of an array, it's critical to understand the difference between an object property/key name (which is always represented as a string) and an array index (which is always a non-negative integer up to the max integer in JavaScript). So, if you have an array and seemingly assign a value to a negative index, you are actually creating a property that is named the negative index and not actually adding to the length of the array or making a new indexed position in the array. We can see that here:

var myArray = ["a", "b", "c"];
myArray[-1] = 15;

console.log(myArray.length);  // 3 not 4
console.log(myArray[-1]);     // 15

// Now to prove that -1 is a string name for a new property and not an index:
console.log(myArray);  // Notice no 15 in the indexed values?

// And, if we enumerate the object (not just the indexes), we'll see that we actually created 
// a property with [-1], not a new index.
for(var prop in myArray){
  // Note that prop is not the value of the property, it's the property name itself
  console.log(typeof prop, prop, myArray[prop]);
}

So, to sum up, Arrays have non-negative integer indexes to store the items that make up the length of the array, but Arrays are also objects and have properties, like all other objects do. Any bracket assignments that use anything other than non-negative integers as the key name will become new properties, not array indices.

Upvotes: 0

developer_hatch
developer_hatch

Reputation: 16224

Take the first is easy, take the last is the size minus one like this:

function firstAndLast(array) {
    var ary = {};
    ary[array[0]] = array[array.length - 1];
    return ary;
}

console.log(firstAndLast([1,2,3]))

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386600

You could pop the last element and take a computed property for the object. (For the first element, you could take Array#shift, if you like to do it in the same manner.)

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

console.log(transformFirstAndLast([1, 2, 3]));

ES5 with a temporary variable.

function transformFirstAndLast(array) {
    var temp = {};
    temp[array[0]] = array.pop();
    return temp;
}

console.log(transformFirstAndLast([1, 2, 3]));

Upvotes: 3

Related Questions