본문 바로가기
카테고리 없음

find content

by pishio 2024. 11. 6.


import * as R from 'ramda';

const findContentEntries = (data) => {
  const findContentRecursively = (item) => {
    if (R.is(Array, item)) {
      // 배열을 순회하면서 각 항목을 재귀적으로 검사
      return R.chain(findContentRecursively, item);
    }
    if (R.is(Object, item)) {
      // 객체에 "content" 키가 있는지 확인하고 해당 객체를 반환
      const contentItems = R.prop('content', item) ? [item] : [];
      // 객체의 모든 값을 재귀적으로 검사하여 결과를 합침
      const nestedItems = R.chain(findContentRecursively, R.values(item));
      return R.concat(contentItems, nestedItems);
    }
    // 배열도 객체도 아닌 경우 빈 배열 반환
    return [];
  };

  return findContentRecursively(data);
};

// 예제 데이터
const data = [
  { content: 'example1', other: 'data1' },
  { nested: { content: 'example2', other: 'data2' } },
  [
    { content: 'example3', other: 'data3' },
    { differentKey: 'no content here' },
    { deeper: [{ content: 'example4' }, { differentKey: 'still no content' }] },
  ],
];

console.log(findContentEntries(data));
// 결과: [
//   { content: 'example1', other: 'data1' },
//   { content: 'example2', other: 'data2' },
//   { content: 'example3', other: 'data3' },
//   { content: 'example4' }
// ]

댓글