根据提供的长度将重复的对象创建到数组中

时间:2019-06-12 04:20:36

标签: javascript typescript typescript-typings

我想根据提供的长度将重复值插入数组:

var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];;
var dataTypesLength= 4;

输出应类似于:

var a = [{displayName: 'bar'},{displayName: 'bar'},{displayName: 'bar'},{displayName: 'bar'}, {displayName:'google'},{displayName:'google'},{displayName:'google'},{displayName:'google'}, {displayName:'mod'}, {displayName:'mod'}, {displayName:'mod'}, {displayName:'mod'}];

我尝试过:

a = a.flatMap( word => Array.from({ dataTypesLength}).fill( word ));

但是我收到打字稿错误,说:Argument of type '{ dataTypesLength: any; }' is not assignable to parameter of type 'ArrayLike<{}>'. Object literal may only specify known properties, and 'dataTypesLength' does not exist in type 'ArrayLike<{}>'

4 个答案:

答案 0 :(得分:2)

只需循环对象数组并使用var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}]; var dataTypesLength= 4; var arr=[]; function fillArray(value, len) { return Array(len).fill(value); } for (var i=0; i<a.length; i++){ var b = fillArray(a[i],dataTypesLength); arr.push(...b); } console.log(arr);即可得到结果。

{{1}}

答案 1 :(得分:2)

您可以将mapObject.assign一起使用,以便每个对象都具有独立的引用

var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];
var dataTypesLength= 4;

a= a.map(obj => { return Array(dataTypesLength).fill(null).map( e => Object.assign({}, obj)) }).flat();
console.log(a)

答案 2 :(得分:2)

您可以使用此(单行解决方案):

a.reduce((acc,x)=>{ acc.push(...new Array(dataTypesLength).fill(x)); return acc;}, [])

说明:

  • 从空数组[]减少输入数组
  • 为每个元素创建一个长度为dataTypesLength的新数组,并用当前元素填充所有新数组 new Array(dataTypesLength).fill(x)
  • 传播新创建的数组并将其推入累加器数组 acc.push(... new Array(dataTypesLength).fill(x))
  • 返回累加器数组

答案 3 :(得分:0)

您可以尝试reduce

var a = [{displayName: 'bar'}, {displayName:'google'}, {displayName:'mod'}];;
var dataTypesLength= 4;

a  = a.reduce(
(f,obj ) => {
var dup = new Array(dataTypesLength); 
f.push(...dup.fill(obj));
return f;
}, [] )