[Javascript] 객체 안의 배열 접근

Jane Yeonju Kim·2022년 1월 26일
1

JavaScript

목록 보기
8/14
post-thumbnail

객체 안의 배열에 접근하기 위해서 for of 반복문을 사용했다.
+ forEach도 추가함!

아래의 myPlants 변수는 배열>객체>list키의 값이 배열로 되어 있는데
여기서 type키가 "trees"인 객체에서 list키의 값중 인덱스 1값의 "pine"을 반환하는 함수를 만든다.

function accessArray() {
  let myPlants = [
    {
      type: "flowers",
      list: [
        "rose",
        "tulip",
        "dandelion"
      ]
    },
    {
      type: "trees",
      list: [
        "fir",
        "pine",
        "birch"
      ]
    }
  ];
   
  let foundValue = null
  for (i of myPlants) {
    // console.log(i)
    if (i['type'] == "trees") {
      foundValue = i['list'][1]
      // console.log(trees)
    }
  }
  return foundValue;
}

console.log(accessArray())  // pine

for 반복문에서 조건부분에 (i of myPlants)를 넣었는데
i를 콘솔로 찍어보면 아래와 같이 myPlants배열의 인덱스 순서대로 출력된다.

{ type: 'flowers', list: [ 'rose', 'tulip', 'dandelion' ] } // 첫번째 i

{ type: 'trees', list: [ 'fir', 'pine', 'birch' ] }  // 두번째 i

그래서 if 조건문안에 i['type']을 넣으면 'flowers', 'trees' 순서로 조건을 검사한다. 일치하는 조건을 만나면 준비해뒀던 변수 foundValue에 넣어준다.

let으로 변수를 선언한다면,
미리 for 반복문 밖에 변수를 선언해둬야 값을 넣어줄 수 있다!



이번에는 forEach() 메서드로 찾아보자!

//  function accessArray() 윗부분은 위와 같음

  let foundValue = null
  myPlants.forEach((i) => { 
    if (i.type == "trees") { 
      foundValue = i.list[1] 
    } 
  })
  return foundValue

forEach()안에 있는 함수는 undefined를 반환하기 때문에
for of 반복문처럼 미리 반복문 밖에 선언해둔 변수에 값을 넣어줘야 한다.

profile
안녕하세요! 김개발자입니다 👩‍💻 🐈

0개의 댓글