159

It seems that when I use a numeric type as a key name in an object, it always gets converted to a string. Is there anyway to actually get it to store as a numeric? The normal typecasting does not seem to work.

Example:

var userId = 1;
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);

Dir Output:

{
    '1': 'a value'
}

What I want is this:

{
    1: 'a value'
}

Advice?

1

11 Answers 11

190

No, this is not possible. The key will always be converted to a string. See Property Accessor docs

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

> var foo = {}
undefined

> foo[23213] = 'swag'
'swag'

> foo
{ '23213': 'swag' }

> typeof(Object.keys(foo)[0])
'string'
18
  • 9
    Even in an array, all property names are converted to strings.
    – Tim Down
    Sep 3, 2010 at 8:11
  • 2
    @Roamer-1888: Not, it isn't. The only difference is that assigning a numeric property to an array affects the array's length property.
    – Tim Down
    Jul 3, 2014 at 8:23
  • 2
    @TimDown, and what I'm saying is that you are wrong. "Setting a numeric property on an Array can affect the length property" is an incorrect statement. Javascript Array properties are completely independent of Array elements. What confuses people is that associative syntax, eg myArray["1"] = foo, appears to be setting a property, whereas it actually sets an array element, but only because "1" is a string representation of an integer, which is complete linguistic nonsense - but that's Javascript. Jul 3, 2014 at 19:25
  • 5
    @Roamer-1888: "Javascript Array properties are completely independent of Array elements" is an incorrect statement. myArray["1"] = foo doesn't just appear to be setting a property, it is in fact setting a property (with a key "1") in every sense of the definition of property. Eg, myArray.hasOwnProperty("1") yields true. Semantically, this property can also be considered an "element" by virtue of having a numeric key, but there is nothing further that distinguishes an array "element" from an array property. Read the spec. If you still disagree, kindly cite your source.
    – Hans
    Jul 11, 2014 at 19:18
  • 2
    @Roamer-1888: I would rather people learned the reality of how the language works (which may well involve some reading of or reference to the spec) than one person's preconceived idea of some (actually non-existent) difference between array and object properties. It sounds like you're projecting ideas from another language onto JavaScript.
    – Tim Down
    Jul 30, 2014 at 13:53
44

In an object, no, but I have found Map extremely useful for this application. Here is where I have used it for numeric keys, a key-based event.

onKeydown(e) {
  const { toggleSidebar, next, previous } = this.props;

  const keyMapping = new Map([
    [ 83, toggleSidebar ],  // user presses the s button
    [ 37, next          ],  // user presses the right arrow
    [ 39, previous      ]   // user presses the left arrow
  ]);

  if (keyMapping.has(e.which)) {
    e.preventDefault();
    keyMapping.get(e.which)();
  }
}
1
  • 4
    The 101 of elegant Ludumdare entries! +1
    – kaiser
    Oct 21, 2019 at 13:01
14

Appears to be by design in ECMA-262-5:

The Property Identifier type is used to associate a property name with a Property Descriptor. Values of the Property Identifier type are pairs of the form (name, descriptor), where name is a String and descriptor is a Property Descriptor value.

However, I don't see a definite specification for it in ECMA-262-3. Regardless, I wouldn't attempt to use non-strings as property names.

6

you can use, Map if you want different datatype as keys

const map1 = new Map();

map1.set(1,3)
map1.set('1','string')

// expected output: 3

console.log(map1.get(1)) //output 3;
console.log(map1.get('1')) //output 'string';
4

Here is the solution. Please tell me the environmental setups if this is not working

const screens = {
    "768": "large",
    "200": "small"
}

const keys = Object.keys(screens).map(key => parseInt(key))
                                         // OR Number(key)

console.log(keys) // Output [200, 768]
1

Do we need something like this?

var userId = 1;var myObject ={};
console.log( typeof userId ); // number
myObject[userId] = 'a value';
console.dir(myObject);

Console: Object

1 : "a value"

0

You can't, but you can always convert keys to a numbers

const data = { 15: "value", name: "Apple" };

const result = Object.keys(data) // get keys as an array
    .map((item) => {
    return parseInt(item); // convert to integer number
    })
    .filter((item) => !isNaN(item)); // remove non number elements

    console.log(result); //Output: [15] 
0
const a = {
    '1': 'a value'
}
//by using a + before any string value it will convert(parse) that into a number
const b = Object.key(a);
console.log(+b); //parse
console.log(typeof b); //number
-1

Per Mozilla: Spread syntax

let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };
const merge = ( ...objects ) => ( { ...objects } );

let mergedObj1 = merge (obj1, obj2);
// Object { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }

let mergedObj2 = merge ({}, obj1, obj2);
// Object { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }

console.log(mergedObj1);
console.log(mergedObj2);

Just order the items before hand and you should get the result you want.

So for your case:

const merge = (...objects) => ({...objects});

// An object with numeric keys
const values = ["a value", "another value", "and another value"];
        
let merged = merge(...values);

console.log(merged);

2
  • this doesn't answer at all the question and how you see those indexes are converted in String type Jul 12, 2021 at 9:09
  • Doing a shallow copy of an object just to convert keys to numbers seems like insane overkill Jan 28, 2022 at 13:11
-2

You can try this:

arr = {}
function f(a,b,c) {
      arr = arguments
}
f("*","#","_")
console.log(arr)
//returns Object { 0: "*", 1: "#", 2: "_" }```
1
  • Writing something like arr = {} is like writing myBool = 'blue'. It's almost maliciously unreadable when it comes to code maintenance and updates. A {} is not an array, it's an object. An array is written [] and calling a spade a shovel doesn't change that fact Jan 28, 2022 at 13:06
-4

In JavaScript, numerical strings and numbers are interchangeable, so

myObject[1] == myObject['1']

If you really want number to be the key for an object, you might want an array (i.e. created with new Array() or []).

2
  • 2
    Thanks for the response but this is not entirely accurate. A numeric will only return as 'number' from a typeof, and vice versa with a string.
    – Spot
    Sep 3, 2010 at 6:09
  • @william 'numerical strings and numbers are interchangeable' is simply not correct. Numbers are Numbers and Strings are Strings. See Object.prototype.toString.call(someObject) The issue is you can't use a Numbers as keys. Oct 11, 2017 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.