'Syntax for creating an array with a key

Edit: total simplification.

Consider this code:

let arr = [42,69]
arr.key = 'lol'

It creates a key value to an array.

However, is it possible to write those two lines in one? I can't find a syntax that works and I'm not sure it is possible.

The reason I want this is because I push the array into another array. I could use an object, but I plan to pop items from it later and it doesn't work on objects.

let all = []
all.push({'0':42,'1':69,'key':'lol'})


Solution 1:[1]

In js you can't have keys in arrays. They only support the index. If you want to assign keys you have to use objects or use the index to do so.

For example like so

const pickedRocks = []

// with objects
pickedRocks.push({value: lastBin.rocks.pop(),key: 500})

// with array index: 0 = value, 1 = key
pickedRocks.push([value: lastBin.rocks.pop(),500])

However since you have a key you could use an object instead of an array alltogether. Unless you want to be able to have duplicates.

const pickedRocks = {}

pickedRocks[500] = lastBin.rocks.pop();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vincent Menzel