javascript - 如果 Javascript 中不存在默认数组过滤器对象,如何获取它
问题描述
我有一个数组:
const data = [
{location: "Phnom Penh", sale: 1000 },
{location: "Kandal", sale: 500 },
{location: "Takeo", sale: 300 },
{location: "Kompot", sale: 700 },
{location: "Prey Veng", sale: 100 },
{location: "Seam Reap", sale: 800 },
{location: "Null", sale: 0}
];
这是我的功能过滤器:
function getSale(data, arr) {
return data
.filter(el => arr.includes(el.location))
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);
result: [{
location: "Phnom Penh",
sale: 1000
},
{
location: "Kompot",
sale: 700
}
]
如果在过滤器中找不到“AA”,我希望它得到“空”对象。
我的目的我想要这样的结果:
result: [
{location: "Phnom Penh", sale: 1000},
{location: "Null", sale: 0},
{location: "Kompot", sale: 700},
{location: "Null", sale: 0}
]
我怎样做?感谢帮助。
解决方案
const data = [
{ location: 'Phnom Penh', sale: 1000 },
{ location: 'Kandal', sale: 500 },
{ location: 'Takeo', sale: 300 },
{ location: 'Kompot', sale: 700 },
{ location: 'Prey Veng', sale: 100 },
{ location: 'Seam Reap', sale: 800 },
{ location: 'Null', sale: 0 },
];
function getSale(data, arr) {
return arr.map(el => {
const found = data.find(obj => obj.location === el);
return found ? found : { location: 'Null', sale: 0 };
});
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);
或者从数据数组创建哈希并直接使用 .map :
const data = [
{ location: 'Phnom Penh', sale: 1000 },
{ location: 'Kandal', sale: 500 },
{ location: 'Takeo', sale: 300 },
{ location: 'Kompot', sale: 700 },
{ location: 'Prey Veng', sale: 100 },
{ location: 'Seam Reap', sale: 800 },
];
const hash = data.reduce((hash, obj) => {
hash[obj.location] = obj;
return hash;
}, {});
function getSale(data, arr) {
return arr.map(el => hash[el] || { location: 'Null', sale: 0 });
}
arr = getSale(data, ['Phnom Penh', 'AA', 'Kompot', 'BB']);
console.log(arr);
推荐阅读
- python - 如何使用 pythran 从其他 py 文件中添加一个 myfunction?
- javascript - 如何调整表单类型下拉列表的文本框大小?
- json - AWS SAM CLI 部署 - 解析开箱即用的问题 secret = get_secret_value_response['SecretString']
- powershell - Exchange PowerShell:如何通过变量将多个值传递给 New-DistributionGroup 命令的 -Members(或 -ManagedBy)参数
- indexing - 如何为此查询优化 Azure Cosmos 索引
- c - 为什么C打印小数点后的浮点值与输入值不同?
- postgresql - 如何在postgresql中将多种日期格式转换为一种格式
- javascript - 如何在材料表中定义tr、td、标签样式
- python - Python tkinter 创建图像
- c# - 将 .NET core 2.0.8 目标应用程序托管到 IIS 时出错