배열 내 객체에서 조건에 해당하는 객체 추출하기

조회수 590회
let input = [
  {
    id: 1,
    name: 'johnny',
  },
  {
    id: 2,
    name: 'ingi',
    children: [
      {
        id: 3,
        name: 'johnson',
      },
      {
        id: 5,
        name: 'steve',
        children: [
          {
            id: 6,
            name: 'lisa',
          },
        ],
      },
      {
        id: 11,
      },
    ],
  },
  {
    id: '13',
  },
];
//재귀함수를 사용해서 아래와 같은 결과물을 얻고 싶은데 '칠드런 내부 객체'에서 맊힘니다...
output = test7(input, 5);
console.log(output); // --> { id: 5, name: 'steve', children: [{ id: 6, name: 'lisa' }] }
  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 1.

    const findById = (input = [], id) => {
        for (const list of input) {
            const found = id === +list.id ? list : findById(list.children, id);
            if (found) {
                return found;
            }
        }
        return null;
    };
    
    console.log(findById(input, 5));
    

    2.

    const flatChildren = li => [li, ...(li.children ? li.children.flatMap(flatChildren) : [])];
    const findById = (input, id) => input.flatMap(flatChildren).find(x => id === +x.id);
    
    console.log(findById(input, 5));
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)