Aus*_*tin 3 javascript arrays object reactjs array.prototype.map
我有一个对象数组看起来像这样.
array = [
{
title: Title1,
votes: 2,
},
{
title: Title2,
votes: 1,
},
{
title: Title3,
votes: 1,
},
];
Run Code Online (Sandbox Code Playgroud)
我想要做的是使用.map将标题推送到一个新的数组,但基于对象的投票数.
对于这个例子,它看起来像这样.
newArray = [Title1, Title1, Title2, Title3]
Run Code Online (Sandbox Code Playgroud)
当我使用React时,使用.map是最好的方法.
不,Array.prototype.map不是最好的.当您想要一个与原始数组长度相同的新数组时,它非常有用.您可以使用Array.prototype.reduce实现您想要的功能:
const array = [ { title: 'Title1', votes: 2 }, { title: 'Title2', votes: 1 }, { title: 'Title3', votes: 1 } ];
const result = array.reduce( (res, el) => res.concat( Array( el.votes ).fill( el.title ) ), [] );
console.log( result );Run Code Online (Sandbox Code Playgroud)
目前还有一个关于Array.prototype.flatMap函数的建议,它可以很好地适用于你的情况,但是还没有太多的浏览器支持:
const array = [ { title: 'Title1', votes: 2 }, { title: 'Title2', votes: 1 }, { title: 'Title3', votes: 1 } ];
const result = array.flatMap( el => Array( el.votes ).fill( el.title ) );
console.log( result );Run Code Online (Sandbox Code Playgroud)