Avoid duplicate keys in object literals

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: javascript-best-practices/no-dupe-keys

Language: JavaScript

Severity: Error

Category: Error Prone

Description

Object literals should not have duplicate keys. If you define an object with duplicate keys, the last one will overwrite any preceding ones.

Non-Compliant Code Examples

var x = { a: b, ['a']: b };
var x = { y: 1, y: 2 };
var x = { '': 1, '': 2 };
var x = { '': 1, [``]: 2 };
var foo = { 0x1: 1, 1: 2};
// should be captured by no-octal
// var x = { 012: 1, 10: 2 };
var x = { 0b1: 1, 1: 2 };
var x = { 0o1: 1, 1: 2 };
var x = { 1n: 1, 1: 2 };
var x = { 1_0: 1, 10: 2 };
var x = { "z": 1, z: 2 };
var foo = {
  bar: 1,
  bar: 1,
  bar() {}
}
var x = { a: 1, get ['a']() {} };
var x = { a: 1, set a(value) {} };
var x = { a: 1, b: { a: 2 }, get b() {} };
var x = ({ '/(?<zero>0)/': 1, [/(?<zero>0)/]: 2 })

// while we can't evaluate the value of the template string we will assume that
// two keys with the exact same template string will evaluate to the same key
const obj = {
    props: {
        [`${classes.foo} ${classes.bar}`]: (): boolean => {
            return null;
        },
        [`${classes.foo} ${classes.bar}`]: (): boolean => {
            return null;
        },
    }
}

Compliant Code Examples

var foo = { __proto__: 1, two: 2};
var x = { foo: 1, bar: 2 };
var x = { '': 1, bar: 2 };
var x = { '': 1, ' ': 2 };
var x = { '': 1, [null]: 2 };
var x = { '': 1, [a]: 2 };
var x = { [a]: 1, [a]: 2 };
+{ get a() { }, set a(b) { } };
var x = { a: b, [a]: b };
var x = { a: b, ...c }
var x = { get a() {}, set a (value) {} };
var x = { a: 1, b: { a: 2 } };
var x = ({ null: 1, [/(?<zero>0)/]: 2 })
var {a, a} = obj
// should be captured by no-octal
// var x = { 012: 1, 12: 2 };
var x = { 1_0: 1, 1: 2 };

// template literals should be valid as long as they are not exactly the same
const obj = {
    props: {
        [`${classes.foo} ${classes.bar}`]: (): boolean => {
            return null;
        },
        [`${classes.baz} ${classes.bla}`]: (): boolean => {
            return null;
        },
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: rtrieu/product-analytics-ui-changes