Is there any way to use a numeric type as an object key?

Viewed 133792

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?

10 Answers

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]

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';

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"

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] 

Per Mozilla: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax[Spread syntax]1

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 } }

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);

You can try this:

arr = {}
function f(a,b,c) {
      arr = arguments
}
f("*","#","_")
console.log(arr)
//returns Object { 0: "*", 1: "#", 2: "_" }```
Related