JavaScript 計數擁有多個鍵中的特定值的物件中的條目數
比方說,我們有如下物件陣列 −
const arr = [
{"goods":"Wheat ", "from":"GHANA", "to":"AUSTRALIA"},
{"goods":"Wheat", "from":"USA", "to":"INDIA"},
{"goods":"Wheat", "from":"SINGAPORE", "to":"MALAYSIA"},
{"goods":"Wheat", "from":"USA", "to":"INDIA"},
];我們需要編寫一個接收此類陣列的 JavaScript 函式。該函式的目的是從原始陣列中返回一個物件陣列,這些物件陣列包含物件的“from”屬性值為“USA”,而物件的“to”屬性值為“INDIA”。
示例
const arr = [
{"goods":"Wheat ", "from":"GHANA", "to":"AUSTRALIA"},
{"goods":"Wheat", "from":"USA", "to":"INDIA"},
{"goods":"Wheat", "from":"SINGAPORE", "to":"MALAYSIA"},
{"goods":"Wheat", "from":"USA", "to":"INDIA"},
];
const findDesiredLength = (arr = [], from = 'USA', to = 'INDIA') => {
const filtered = arr.filter(el => {
if(el.from === from && el.to === to){
return true;
}
});
const { length: l } = filtered || [];
return l;
};
console.log(findDesiredLength(arr));輸出
控制檯中的輸出為 −
2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP