포시코딩

Array.prototype.find() 본문

JavaScript

Array.prototype.find()

포시 2022. 7. 8. 12:25
728x90

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

 

Array.prototype.find() - JavaScript | MDN

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.

developer.mozilla.org

 

오브젝트로 이루어진 배열에서 id 값이 2인 오브젝트를 찾고 싶을 때 쓸 수 있는 문법

let data = [
    {
      id : 0,
      title : "White and Black",
      content : "Born in France",
      price : 120000
    },
    {
      id : 1,
      title : "Red Knit",
      content : "Born in Seoul",
      price : 110000
    },
    {
      id : 2,
      title : "Grey Yordan",
      content : "Born in the States",
      price : 130000
    }
  ];

data 안에서 id 가 2인 오브젝트의 title 을 찾고 싶을 경우 아래와 같이 하면된다. 

let result = data.find( x => x.id == 2 );
console.log(result.title);

 

728x90