0

Essentially I am creating object's key (year) using for-loop. However, I would like to have it that the first key of the object will be the initial key I manually created.

However, it ends up being pushed all the way to the last.

I have the following code:

const VEHICLE_YEARS = () => {
    const vehicleYears = {}
    vehicleYears['initial'] = 'Choose One'
    const startYear = 2013
    const endYear = new Date().getFullYear()
    for (let year = startYear; year <= endYear; year++) {
        vehicleYears[year] = year
    }

    return vehicleYears
}
VEHICLE_YEARS()

it sends up like this:

{ 
  '2013': 2013,
  '2014': 2014,
  '2015': 2015,
  '2016': 2016,
  '2017': 2017,
  initial: 'Select One'
 }
Alejandro
  • 1,906
  • 4
  • 27
  • 58

1 Answers1

1

Simple Object does not provide what you want. You need Map there.

You need this:

const map = new Map();
map.set('initial', 'Select one');
map.set('2013', '2013');
map.set('2014', '2014');
map.set('2015', '2015');
map.set('2016', '2016');
map.set('2017', '2017');
// etc

To iterate you can use for..of:

for (const [key, value] of map) {
  console.log(key, value)
}

// the result
initial Select one
2013 2013
2014 2014
2015 2015
2016 2016
2017 2017

If you iterate though map with for of it is guarantied that you will iter throught entries in order as you added them to the map. From docs:

A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.

Also, to iterate through entries you have Map.prototype.forEach.

map.forEach((val, key) => console.log(key ,val))
Sharikov Vladislav
  • 6,110
  • 4
  • 39
  • 78