我想根据提供的长度将重复值插入数组:
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<{}>'
答案 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)
您可以将map
与Object.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;}, [])
说明:
答案 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;
}, [] )