JavaScript/객체

[JavaScript]객체의 값으로 키를 가져오는 방법

DevStory 2022. 10. 12.

객체의 값으로 키를 가져오는 방법

JavaScript에서 객체의 프로퍼티는 Key-Value 쌍 구조로 이루어진 데이터 집합입니다.

 

예를 들어, Person이라는 객체의 name 프로퍼티의 Key는 name이고 Value는 'Hong Gil Dong'입니다.

const Person = {
  name: 'Hong Gil Dong',  // Key: name,   Value: '홍길동'
  age: 20,                // Key: age,    Value: 20
  gender: 'male'          // Key: gender, Value: 'male'
};

객체의 키에 해당하는 값은 점(.) 표기법 또는 대괄호([]) 표기법을 사용하여 가져올 수 있지만, 값에 해당하는 키를 가져오는 방법은 쉽지 않습니다.

 

값에 해당하는 키를 가져오려면, Object.keys() 메서드를 사용하여 객체의 모든 키를 배열로 가져온 다음 find() 메서드나 filter() 메서드를 사용해야 합니다.

 

다음 예제는 Object.keys() 메서드 사용 방법과 반환 결과를 보여줍니다.

const Person = {
  name: 'Hong Gil Dong',  // Key: name,   Value: '홍길동'
  age: 20,                // Key: age,    Value: 20
  gender: 'male'          // Key: gender, Value: 'male'
};

console.log(Object.keys(Person)); // ['name', 'age', 'gender']

방법 1. find 메서드

배열의 find() 메서드는 특정 조건을 만족하는 요소를 반환합니다.

 

다음 예제는 값이 4인 Person 객체의 키를 가져옵니다.

const Person = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5
};

const keysOfPerson = Object.keys(Person);

const key = keysOfPerson.find((key) => Person[key] === 4);

console.log(key); // four

 

다음 예제는 값이 10인 Person 객체의 키를 가져옵니다.

const Person = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5
};

const keysOfPerson = Object.keys(Person);

const key = keysOfPerson.find((key) => Person[key] === 10);

console.log(key); // undefined

특정 조건을 만족하는 요소가 없는 경우 find() 메서드는 undefined를 반환합니다.

 

다음 예제는 값이 3 이상인 Person 객체의 키를 가져옵니다.

const Person = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5
};

const keysOfPerson = Object.keys(Person);

const key = keysOfPerson.find((key) => Person[key] >= 3);

console.log(key); // three

특정 조건을 만족하는 요소가 여러 개인 경우 find() 메서드는 배열의 첫 번째 위치(0번째 인덱스)와 가장 인접한 요소를 반환합니다. 따라서, 값이 3 이상인 요소 중 첫 번째 위치(0번째 인덱스)와 가장 인접한 요소인 three가 반환되었습니다. 특정 조건을 만족하는 모든 요소를 가져오고 싶은 경우 find() 메서드가 아닌 filter() 메서드를 호출해야 합니다.


방법 2. filter 메서드

배열의 filter() 메서드는 특정 조건을 만족하는 요소를 배열로 반환합니다.

 

다음 예제는 값이 3 이상인 Person 객체의 모든 키를 가져옵니다.

const Person = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5
};

const keysOfPerson = Object.keys(Person);

const key = keysOfPerson.filter((key) => Person[key] >= 3);

console.log(key); // ['three', 'four', 'five']

 

다음 예제는 값이 10인 Person 객체의 키를 가져옵니다.

const Person = {
  one: 1,
  two: 2,
  three: 3,
  four: 4,
  five: 5
};

const keysOfPerson = Object.keys(Person);

const key = keysOfPerson.filter((key) => Person[key] === 10);

console.log(key); // []

특정 조건을 만족하는 요소가 없는 경우 filter() 메서드는 빈 배열을 반환합니다.

반응형

댓글