假设我们有一个像这样的对象数组-
const arr = [ {code: "AA", gender:"male", DOB:"2000-05-15"}, {code: "AA", gender:"female", DOB:"2015-05-15"}, {code:"A0", gender:"female", DOB:"2005-01-01"}, {code: "A1", gender:"male", DOB:"2015-01-15"} ];
我们需要编写一个JavaScript函数,该函数接受一个这样的对象数组。该函数应计算数组中重复对象的数量(基于对象的“ code”属性),并为每个唯一对象分配一个新的count属性。
如果年龄(使用“ DOB”和当前日期计算)小于18岁,则该函数还应为每个唯一对象分配一个子属性,其值将为1,否则为0。
为此的代码将是-
const arr = [ {code: "AA", gender:"male", DOB:"2000−05−15"}, {code: "AA", gender:"female", DOB:"2015−05−15"}, {code:"A0", gender:"female", DOB:"2005−01−01"}, {code: "A1", gender:"male", DOB:"2015−01−15"} ]; const groupAndAdd = (arr = []) => { const result = new Map(); let nowYear = new Date().getYear(); arr.forEach(el => { let item = result.get(el.code) || {code: el.code, count: 0, female: 0, child: 0 }; item.count++; item.female += el.gender === "female"; item.child += nowYear − new Date(Date.parse(el.DOB)).getYear() <18; result.set(item.code, item); }); return result; }; console.log(groupAndAdd(arr));
输出结果
控制台中的输出将是-
Map { 'AA' => { code: 'AA', count: 2, female: 1, child: 1 }, 'A0' => { code: 'A0', count: 1, female: 1, child: 1 }, 'A1' => { code: 'A1', count: 1, female: 0, child: 1 } }