Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

유사한 키 JavaScript를 사용하여 배열의 객체 병합

<시간/>

다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -

const arr = [
   {id: 1, h1: 'Daily tests'},
   {id: 2, h1: 'Details'},
   {id: 1, h2: 'Daily classes'},
   {id: 3, h2: 'Results'},
   {id: 2, h3: 'Admissions'},
   {id: 1, h4: 'Students'},
   {id: 2, h5: 'Alumni'},
   {id: 3, h3: 'Appreciations'},
   {id: 1, h5: 'Tiny Tots'},
   {id: 1, h6: 'Extras'},
];

이 배열을 동일한 id를 가진 모든 제목(h1, h2,h3 …)이 동일한 객체 내부에 묶이는 배열로 변환하는 함수를 작성해야 합니다. 따라서 이 함수의 코드를 작성해 보겠습니다 -

예시

const arr = [
   {id: 1, h1: 'Daily tests'},
   {id: 2, h1: 'Details'},
   {id: 1, h2: 'Daily classes'},
   {id: 3, h2: 'Results'},
   {id: 2, h3: 'Admissions'},
   {id: 1, h4: 'Students'},
   {id: 2, h5: 'Alumni'},
   {id: 3, h3: 'Appreciations'},
   {id: 1, h5: 'Tiny Tots'},
   {id: 1, h6: 'Extras'},
];
const clubArray = (arr) => {
   return arr.reduce((acc, val, ind) => {
      const index = acc.findIndex(el => el.id === val.id);
      if(index !== -1){
         const key = Object.keys(val)[1];
         acc[index][key] = val[key];
      } else {
         acc.push(val);
      };
      return acc;
   }, []);
};
console.log(clubArray(arr));

출력

콘솔의 출력은 다음과 같습니다. -

[
   {
      id: 1,
      h1: 'Daily tests',
      h2: 'Daily classes',
      h4: 'Students',
      h5: 'Tiny Tots',
      h6: 'Extras'
   },
   { id: 2, h1: 'Details', h3: 'Admissions', h5: 'Alumni' },
   { id: 3, h2: 'Results', h3: 'Appreciations' }
]