在JavaScript对象中查找重复键 [英] Finding duplicate keys in JavaScript object

查看:79
本文介绍了在JavaScript对象中查找重复键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其唯一目的是在对象中提供大量的键/值对。它看起来像这样:

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

现在,当我引用该文件并引用some_key时,我得到了意外的重复值,因为JavaScript会存储最后声明的密钥。

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.

我想编写一个单元测试,检查此对象是否有意外的重复密钥。问题是JavaScript已经删除了重复项。如何通过单元测试完成此检查?

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

推荐答案

添加use strict; 到文件的顶部。用法示例:

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

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

编辑:由于ES6计算的属性值,此答案不再是严格最新的。如果需要,可以将对象编写为JSON对象(如果可能的话),并通过 http:// www .jslint.com / ,它将检查重复的密钥。请参阅:use strict;现在允许重复的属性?

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?

这篇关于在JavaScript对象中查找重复键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆