1

I want to create a simple object.

Example: {house:'house, cat: 'cat', dog: 'dog', 45: 45 }

However javascript always takes the numbers in my array

Example: 45 - 45:45

and places it at the very top/front of my object.

Question 1: Why does this happen?

Question 2: How can I create my object with the items in order as presented in the array (yes I know that how they are placed within an object isn't important, since they all have keys) but please help.

let jakesLife = [
    'house',
    'cat',
    'dog',
    45
    ]
function x () {
    let obj = {};
    for (let i = 0; i < jakesLife.length; i++) {
        obj[jakesLife[i]] = jakesLife[i];
    }
    return obj;
}
x()
R. Antenor
  • 11
  • 2

1 Answers1

1

Objects are unordered. That's why we have arrays. Your ordered list of keys should be sufficient to get ordered access when you need it.

You could make an object type that handles this if you need it often.

let jakesLife = [
  'house',
  'cat',
  'dog',
  45
]

class Ordered {
  constructor(arr) {
    this.__keys = arr;
    arr.forEach(k => this[k] = k)
  }
  
  each(callback) {
    this.__keys.forEach(k => callback(this[k], k))
  }
}

var o = new Ordered(jakesLife);
o.each(v => console.log(v));
spanky
  • 2,768
  • 8
  • 9
  • Given that every property value is the same as the property key, I don't see any reason to store them as properties of anything at all. – Bergi Sep 07 '17 at 21:36
  • @Bergi: Toy example. :) – spanky Sep 07 '17 at 21:36
  • Even then, if there was an additonal mapping for "actual values" (besides the array with the ordering), I don't see a reason to copy the values to properties of the instances instead of just storing the mapping itself in `.__values` or something. – Bergi Sep 07 '17 at 21:40