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

更新於: 2020 年 11 月 23 日

瀏覽量 256

開啟您的事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.