基于另一个对象数组创建对象数组 JavaScript
javascriptweb developmentfront end technologyobject oriented programming
假设,我们有一个对象数组,其中包含有关某些用户的喜好的数据,例如 −
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' } ]