假设我们有一个这样的对象数组-
const arr = [{ country: "cananda", count: 2 }, { country: "jamaica", count: 2 }, { country: "russia", count: 1 }, { country: "india", count: 3 }, { country: "spain", count: 2 }, { country: "portugal", count: 1 }, { country: "italy", count: 1 }];
我们需要编写一个函数,该函数接受此数组,对其进行映射并返回一个字符串数组,该字符串的国家/地区名称对于每个特定对象重复“计数”次数。
因此,此对象的函数输出应为-
['canada', 'canada', 'jamaica', 'jamaica', 'russia', 'india', 'india', 'india','spain', 'spain','portugal', 'italy']
让我们为该函数编写代码。我们将在这里使用Array.prototype.reduce()方法-
const arr = [{ country: "canada", count: 2 }, { country: "jamaica", count: 2 }, { country: "russia", count: 1 }, { country: "india", count: 3 }, { country: "spain", count: 2 }, { country: "portugal", count: 1 }, { country: "italy", count: 1 }]; const repeatCount = (arr) => { return arr.reduce((acc, val) => { let { count, country } = val; while(count--){ acc.push(country); } return acc; }, []); }; console.log(repeatCount(arr));
输出结果
控制台中的输出将为-
[ 'canada', 'canada', 'jamaica', 'jamaica', 'russia', 'india', 'india', 'india', 'spain', 'spain', 'portugal', 'italy' ]