假设我们有两个数组,一个是String文字,另一个是object。
const data = [{ name: 'Kamlesh Kapasi', uid: 123 }, { name: 'Mahesh Babu', uid: 129 }, { name: 'Akshay Kapoor', uid: 223 }, { name: 'Vikas Gupta', uid: 423 }, { name: 'Mohit Dalal', uid: 133 }, { name: 'Rajkumar Hirani', uid: 233 }, { name: 'Joy', uid: 127 }]; const names = ['Joy', 'Rajkumar Hirani', 'Akshay Kapoor', 'Mahesh Babu', 'Mohit Dalal', 'Kamlesh Kapasi', 'Vikas Gupta']
我们的工作是编写一个遍历names数组并构造Numbers数组的函数,该数组包含特定名称的uid,其顺序与出现在names数组中的顺序相同。
让我们为该函数编写代码-
const data = [{ name: 'Kamlesh Kapasi', uid: 123 }, { name: 'Mahesh Babu', uid: 129 }, { name: 'Akshay Kapoor', uid: 223 }, { name: 'Vikas Gupta', uid: 423 }, { name: 'Mohit Dalal', uid: 133 }, { name: 'Rajkumar Hirani', uid: 233 }, { name: 'Joy', uid: 127 }]; const names = ['Joy', 'Rajkumar Hirani', 'Akshay Kapoor', 'Mahesh Babu', 'Mohit Dalal', 'Kamlesh Kapasi', 'Vikas Gupta'] const mapId = (arr, names) => { return names.reduce((acc, val) => { const index = arr.findIndex(el => el.name === val); return acc.concat(arr[index].uid); }, []); } console.log(mapId(data, names));
输出结果
控制台中的输出将为-
[ 127, 233, 223, 129, 133, 123, 423 ]