假设我们有两个字符串数组,其中包含有关某些用户的数据,如下所示:
const users = ['Rahul', 'Dinesh', 'Rohit']; const data = ["SOP1", "SOP2","SOP3","SOP4"];
我们需要编写一个JavaScript函数,该函数接受两个这样的数组并返回一个新的对象数组。
对于用户和数据数组的每种可能组合,新数组应包含一个对象。
因此,对于上述数组,输出应类似于-
const output = [ { User: 'Rahul', SOP: 'SOP1' }, { User: 'Rahul', SOP: 'SOP2' }, { User: 'Rahul', SOP: 'SOP3' }, { User: 'Rahul', SOP: 'SOP4' }, { User: 'Dinesh', SOP: 'SOP1' }, { User: 'Dinesh', SOP: 'SOP2' }, { User: 'Dinesh', SOP: 'SOP3' }, { User: 'Dinesh', SOP: 'SOP4' }, { User: 'Rohit', SOP: 'SOP1' }, { User: 'Rohit', SOP: 'SOP2' }, { User: 'Rohit', SOP: 'SOP3' }, { User: 'Rohit', SOP: 'SOP4' } ];
为此的代码将是-
const users = ['Rahul', 'Dinesh', 'Rohit']; const data = ["SOP1", "SOP2","SOP3","SOP4"]; const multiplyUserData = (users = [], data = []) => { const res = []; users.forEach(user => { data.forEach(el => { res.push({ 'user': user, 'sop': el }); }); }); return res; }; console.log(multiplyUserData(users, data));
输出结果
控制台中的输出将是-
[ { user: 'Rahul', sop: 'SOP1' }, { user: 'Rahul', sop: 'SOP2' }, { user: 'Rahul', sop: 'SOP3' }, { user: 'Rahul', sop: 'SOP4' }, { user: 'Dinesh', sop: 'SOP1' }, { user: 'Dinesh', sop: 'SOP2' }, { user: 'Dinesh', sop: 'SOP3' }, { user: 'Dinesh', sop: 'SOP4' }, { user: 'Rohit', sop: 'SOP1' }, { user: 'Rohit', sop: 'SOP2' }, { user: 'Rohit', sop: 'SOP3' }, { user: 'Rohit', sop: 'SOP4' } ]