Menggabungkan dua tatasusunan Javascript ke dalam tatasusunan hasil tunggal berdasarkan kunci biasa, serupa dengan operasi JOIN dalam SQL.
const innerJoin = (xs, ys, sel) => xs.reduce((zs, x) => ys.reduce((zs, y) => // cartesian product - all combinations zs.concat(sel(x, y) || []), // filter out the rows and columns you want zs), []);
const userProfiles = [ {id: 1, name: "Ashok"}, {id: 2, name: "Amit"}, {id: 3, name: "Rajeev"}, ]; const questions = [ {id: 1, text: "text1", createdBy: 2}, {id: 2, text: "text2", createdBy: 2}, {id: 3, text: "text3", createdBy: 1}, {id: 4, text: "text4", createdBy: 2}, {id: 5, text: "text5", createdBy: 3}, {id: 6, text: "text6", createdBy: 3}, ];
const result = innerJoin(userProfiles, questions, ({id: uid, name}, {id, text, createdBy}) => createdBy === uid && {id, text, name});
Open your browser console to see the output. [ { id: 1, text: 'text3', name: 'Ashok' }, { id: 2, text: 'text1', name: 'Amit' }, { id: 2, text: 'text2', name: 'Amit' }, { id: 4, text: 'text4', name: 'Amit' }, { id: 5, text: 'text5', name: 'Rajeev' }, { id: 6, text: 'text6', name: 'Rajeev' } ]
Atas ialah kandungan terperinci Bagaimana untuk Melakukan Inner Join pada Tatasusunan Javascript?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!