假设我们有一个对象数组,其中包含有关某些用户喜欢的数据,例如:
const arr = [ {"user":"dan","liked":"yes","age":"22"}, {"user":"sarah","liked":"no","age":"21"}, {"user":"john","liked":"yes","age":"23"}, ];
我们需要编写一个包含一个这样的数组的JavaScript函数。该函数应基于此数组构造另一个数组,如下所示:
const output = [ {"dan":"yes"}, {"sarah":"no"}, {"john":"yes"}, ];
const arr = [ {"user":"dan","liked":"yes","age":"22"}, {"user":"sarah","liked":"no","age":"21"}, {"user":"john","liked":"yes","age":"23"}, ]; const mapToPair = (arr = []) => { const result = arr.map(obj => { const res = {}; res[obj['user']] = obj['liked']; return res; }); return result; }; console.log(mapToPair(arr));
输出结果
控制台中的输出将是-
[ { dan: 'yes' }, { sarah: 'no' }, { john: 'yes' } ]