0

How can I assert the keys of an object are not parsed as numbers?
Basically both 3 and "3" should raise an error.

I'm using Chai and this is what I have done so far:

it("shouldn't have numeric keys", () => {
  Object.keys(obj).map(key => chai.assert.isNotNumber(key));  // where key is "3"
});

This doesn't raise an error if the key is "3". Thank you.

By the way, I need this to guarantee the object property order accordingly to Does JavaScript Guarantee Object Property Order?

isar
  • 1,661
  • 1
  • 20
  • 39
  • 2
    Object property names cannot be numbers. They can only be strings or Symbol instances. In particular, `Object.keys()` always returns an array of strings. – Pointy Apr 08 '19 at 13:13
  • So, how can I assert `"3"` is not a valid key? Should I use parseInt or Chai has got something more convenient? – isar Apr 08 '19 at 13:25
  • 1
    Well, as far as JavaScript is concerned there's nothing wrong with the string `"3"` as a property name. You could test for `isNaN(+key)` if for some reason your application doesn't like numeric property names. – Pointy Apr 08 '19 at 13:27
  • As to the last statement in the question, relying on property creation order in general is a fragile coding practice. Yes, the order is standardized, but it's based on the "life experience" of each individual object and it's not really under direct control of the application code. – Pointy Apr 08 '19 at 13:29
  • It sounds like you need to check if it is a number, or a string that parses to a number. You could try converting it and testing if the result is a number, or apply a RegEx test. – scunliffe Apr 08 '19 at 13:41
  • @scunliffe thank you, Pointy solution's works already really well. That was the answer for me. – isar Apr 08 '19 at 13:44

0 Answers0