根据另一个对象数组创建对象数组 JavaScript
假设我们有一个对象数组,其中包含有关某些用户喜欢的数据,如下所示 −
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' } ]
广告