我有一个看起来像这样的对象数组。
array = [
{
title: Title1,
votes: 2,
},
{
title: Title2,
votes: 1,
},
{
title: Title3,
votes: 1,
},
];
我想做的是使用 .map 将标题插入一个新数组,但基于该对象的投票数。
对于这个例子,它看起来像这样。
newArray = [Title1, Title1, Title2, Title3]
在我使用 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 );
目前还有一个proposal for an 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 );
关于javascript - .map 对象标题数组到一个基于票数的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52880674/