[英]Create new array of objects by grouping array of objects based on property value of each object in javascript
[英]Create array of objects based on length; each object has a property with the index + 1 as its value
我想將我丑陋的代碼改進為更干凈和簡單的東西。 如何縮短此代碼?
if (this.foo < 2) {
return (this.result = [ { year: 1 } ]);
}
if (this.foo < 3) {
return (this.result = [ { year: 1 }, { year: 2 } ]);
}
if (this.foo < 4) {
return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 } ]);
}
if (this.foo < 5) {
return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 }, { year: 4 } ]);
}
if (this.foo < 6) {
return (this.result = [ { year: 1 }, { year: 2 }, { year: 3 }, { year: 4 }, { year: 5 } ]);
}
使用Array
創建一個數組,並使用Array.prototype.map
。
function func(foo) { return Array(foo).fill().map((f, i) => ({ year: i + 1 })); } console.log(func(1)); console.log(func(3));
您所展示的內容與此等效(除了這超出了五個元素,而且還超出了另一個方向的一個):
return this.result = Array.from({
length: Math.floor(this.foo)
}, (_value, index) => ({
year: index + 1
}));
這假定此語句位於 function 內(否則, return
將不起作用)。
更合理的長度可能是 Math.max(0, Math.min(2 ** 32 - 1 Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo)))
,它將長度限制為至少 0 和最多 2 32 - 1, 最大數組長度。
如果您希望數組中始終至少有一個元素,請改用Math.max(1,
... )
。
返回一個作業(即return this.result =
... ;
)是不受歡迎的。 最佳做法是將這些語句2分開:
this.result = Array.from({
length: Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo)))
}, (_value, index) => ({
year: index + 1
}));
return this.result;
Array.from
與 arguments 一起使用:第一個是“類似數組”的 object { length: Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo))) }
它被轉換為正確的Array
object。 在這種情況下,將初始化一個長度為Math.floor(this.foo)
的數組(限制在可能的數組長度范圍內)。 第二個參數將某個index
處的每個值映射到 object ,其中year
屬性的值index + 1
。 _value
未使用(無論如何它是undefined
的)。
使用Array.from(
array-like ,
mapping-function )
優於.fill().map(
… )
的優點是在 memory 中只創建了一個數組。 Array(
... ).fill().map(
... )
創建兩個新的 arrays:第一個在Array(
... ).fill()
,第二個在.map(
... )
。 因此, Array.from
方法更節省內存。
1 :也許很快我們就會得到一個Math.clamp
方法……
2 :從技術上講,這將是等效的。 如果this.result
是一個 getter / setter,可能會有明顯的差異。
const result = Array.from({
length: Math.max(0, Math.min(2 ** 32 - 1, Math.floor(this.foo)))
}, (_value, index) => ({
year: index + 1
}));
this.result = result;
return result;
試試這個oneliner
let x=3;
let result = [ ...Array(x).keys() ].map(item=> {return{"year":item}});
console.log(result);
let arr = [];
for(let i = 1; i<this.foo;i++){
arr.push({ 'year':i})
};
console.log(arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.