计算对象中具有多个键中特定值的条目数
假设我们有一个像这样的对象数组-
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