배열 내 객체에서 조건에 해당하는 객체 추출하기
조회수 599회
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));
댓글 입력