JS中的reduce歸并和...擴展運算符,可以重構一個對象

2023-08-31 15:07:51
```javascript arr = [{ a: 1, b: 2, subjects: [{ str: 'c', number: 3 }, { str: 'd', number: 4 }, { str: 'e', number: 5 }] }, { a: 11, b: 12, subjects: [{ str: 'c', number: 23 }, { str: 'd', number: 34 }, { str: 'e', number: 65 }] }]; const result = arr.map(obj => { const a = obj.a; const b = obj.b; //console.log(a); //console.log(b); const subjectObj = obj.subjects.reduce((acc, subject) => { acc[subject.str] = subject.number; //console.log(acc); return acc; }, {}); /* ...subjectObj const c = acc.c; const d = acc.d; const e = acc.e; */ /* console.log(subjectObj); console.log({ a,b, ...subjectObj});*/ return { a,b, ...subjectObj }; }); console.log(result); ```