[ js ]조건을 만족하는 배열요소 가져오기- find()

전상욱·2021년 5월 24일
0

js & ts 

목록 보기
10/12
  • 유저 정보가 담긴 배열에서 ID를 기준으로 정보를 가져오고 싶을때

find

배열.find(콜백함수) : 콜백 함수 조건에 맞는 첫 요소( 첫요소 첫요소 첫요소)
배열.findIndex(테스트함수) : 콜백 함수 조건에 맞는 첫 요소의 인덱스

html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="/src/styles.css" />
  </head>
  <body>
    <input type="text" id="search">
    <p id="result"></p>
    <script src="./src/index.js"></script>
  </body>
</html>

javacript

find로 입력한 아이디 값과 userData의 id 값을 비교함.

const userData = [
  { id: 1, name: "딸기" },
  { id: 2, name: "바나나" },
  { id: 3, name: "사과" }
];

const search = document.querySelector("#search");
const result = document.querySelector("#result");

search.addEventListener("keyup", () => {
  const searchId = Number(search.value)
  findUser(searchId)
});

function findUser (searchId) {
  const targetData = userData.find((data) => data.id === searchId)
  console.log(targetData)
  if(targetData == null) {
    result.textContent='유저없음'
    return
  }
profile
someone's opinion of you does not have to become your reality

0개의 댓글