我想獲取所有等于某個數字的值并計算每個物件的數量。
我的代碼如下所示:
var countItems = {
"aa":"70",
"bb":"70",
"cc":"80",
"dd":"90",
"ee":"90",
"ff":"90"
}
現在我想做的就是在下半場數一數。
比如有兩個“70”,一個“80”,三個90。那么我可以給變數賦值:
var firstCounter = ?? // 2
var secondCounter = ?? // 1
var thirdCounter = ?? // 3
??我不知道這里發生了什么。
如果它的結構不同,如下所示,我可以這樣做:
let firstCounter = 0;
for (let i = 0; i < countItems.length; i ) {
if (countItems[i].status === '70') firstCounter ;
}
let secondCounter = 0;
for (let i = 0; i < countItems.length; i ) {
if (countItems[i].status === '80') secondCounter ;
}
let thirdCounter = 0;
for (let i = 0; i < countItems.length; i ) {
if (countItems[i].status === '90') thirdCounter ;
}
但問題是,我擁有的原始代碼的結構不是這樣,所以我不確定如何調整它。
如何計算原始串列 ( var countItems) 中的專案,以便找出每個值是多少?
uj5u.com熱心網友回復:
您可以使用Object.values(countItems)來獲取一個如下所示的陣列:["70","70","80","90","90","90"]然后使用for回圈有條件地增加您想要的任何計數器,或者使用類似Array.reduce或Array.filter計算您需要的元素。
uj5u.com熱心網友回復:
您可以reduce像這樣創建一個計數的哈希映射:
const countItems = [
{ data: 'aa', status: '70' },
{ data: 'bb', status: '70' },
{ data: 'cc', status: '80' },
{ data: 'dd', status: '90' },
{ data: 'ee', status: '90' },
{ data: 'ff', status: '90' },
];
const countedHash = countItems.reduce((acc, curr) => {
if (!acc[curr.status])
acc[curr.status] = 1
else
acc[curr.status] = 1
return acc
}, {})
/* print out the results */
console.log(countedHash)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
uj5u.com熱心網友回復:
您可以像這樣訪問物件鍵:
countItems["aa"] // it will return "70"
您還可以在物件上回圈(如果您想像在示例中那樣做):
for (const item in countItems) {
console.log(countItems[item])
if (countItems[item] == "70") firstCounter ;
}
uj5u.com熱心網友回復:
Object.values()并且reduce()都是正確的想法。合起來...
var countItems = {
"aa":"70",
"bb":"70",
"cc":"80",
"dd":"90",
"ee":"90",
"ff":"90"
};
let counts = Object.values(countItems).reduce((acc, value) => {
if (!acc[value]) acc[value] = 0;
acc[value] ;
return acc;
}, {});
let [theFirstValue, theSecondValue, theThirdValue] = Object.values(counts)
console.log(theFirstValue, theSecondValue, theThirdValue);
uj5u.com熱心網友回復:
const countItems = [
{ data: 'aa', status: '70' },
{ data: 'bb', status: '70' },
{ data: 'cc', status: '80' },
{ data: 'dd', status: '90' },
{ data: 'ee', status: '90' },
{ data: 'ff', status: '90' },
];
var countValues = Object.values(countItems);
let obj ={}
for(let val of countValues){
if(!obj[val.status]){
obj[val.status] = 1
}else{
obj[val.status] = 1
}
}
console.log(obj)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482205.html
標籤:javascript 数组 循环 数数
上一篇:改變參考值時保持相同的退化步長
下一篇:如何重命名函式內的列?
