Guy
Guy

Reputation: 67260

Finding duplicate keys in JavaScript object

I have a file whose sole purpose is to provide an enormous collection of key/value pairs in an object. It looks something like this:

var myobj = {
   some_key: 'some value',
   another_key: 'another value',
   // thousands of other key/value pairs...
   some_key: 'accidental duplicate key with different value'
};

Now when I reference that file and reference the some_key I get the accidental duplicate value because JavaScript will store the last declared key.

I want to write a unit test that checks this object for accidental duplicate keys. Problem is that JavaScript has already stripped out the duplicates. How would I accomplish this checking through unit tests?

(One answer would be to manually parse the file using string parsing to find the duplicates. This is brittle and I'd want to stay away from this.)

Upvotes: 3

Views: 7505

Answers (1)

soktinpk
soktinpk

Reputation: 3888

Add "use strict"; to the top of your file. Example usage:

(function() {
  "use strict";
  // Throws a syntax error
  var a = {
    b: 5,
    b: 6
  };
})();

Edit: This answer is no longer strictly up to date due to ES6 computed property values. If you want, you can write your object as a JSON object (if that's possible) and put it through http://www.jslint.com/, which will check for duplicate keys. See as well: "use strict"; now allows duplicated properties?

Upvotes: 8

Related Questions