본문 바로가기

JavaScript/Lodash

[Lodash] _.find() 함수 설명 및 사용 예제/예시

반응형

구문(Syntax)

_.find(collection, [predicate=_.identity], [fromIndex=0])
컬렉션의 요소를 반복하여 조건자(predicate)가 true를 반환하는 첫 번째 요소를 반환합니다. 조건자는 세 가지 인수(값, 인덱스|키, 컬렉션)를 사용하여 호출됩니다.
Iterates over elements of collection, returning the first element predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).

매개변수(Arguments)

- collection (Array|Object): 검사할 컬렉션입니다.
- [predicate=_.identity] (Function): 반복마다 호출되는 함수입니다.
- [fromIndex=0] (number): 검색할 인덱스입니다.

- collection (Array|Object): The collection to inspect.
- [predicate=_.identity] (Function): The function invoked per iteration.
- [fromIndex=0] (number): The index to search from.

반환 값(Returns)

(*): 일치하는 요소를 반환합니다. 일치하는 요소가 없으면 undefined를 반환합니다.

(*): Returns the matched element, else undefined.

 

예제(Example)

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

 

예제 1) 두 번째 인자로 원하는 함수를 직접 작성할 수 있습니다. 

_.find(users, function(o) { return o.age < 40; });
// users 배열의 객체를 순회하면서 age가 40보다 작은 요소들 중 첫번째 객체를 리턴합니다.
// 반환값: {user: "barney", age: 36, active: true}

예제 2) 두 번째 인자로 `_.matches` 함수의 축약형을 함수 대신 이용할 수  있습니다.

_.find(users, { 'age': 1, 'active': true });
// users 배열의 객체를 순회하면서 age가 1이고 active가 true인 첫번째 객체를 리턴합니다.
// 반환값: {user: "pebbles", age: 1, active: true}

예제 3) 두 번째 인자로 `_.matchesProperty` 함수의 축약형을 함수 대신 이용할 수  있습니다.

_.find(users, ['active', false]);
// users 배열의 객체를 순회하면서 active가 false인 첫번째 객체를 리턴합니다.
// 반환값: {user: "fred", age: 40, active: false}

예제 4) 두 번째 인자로 `_.property` 함수의 축약형을 함수 대신 이용할 수  있습니다.

_.find(users, 'active');
// users 배열의 객체를 순회하면서 active가 true인 첫번째 객체를 리턴합니다.
// 반환값: {user: "barney", age: 36, active: true}

 

 

Reference

 

반응형