javascript - Filtering out items from an API call if they share the same value on a key
问题描述
I've got a dataset that returns an array of objects and I want to filter out any of the objects that have the same value on the name key. A small example of the data returned:
{
"product_id": 8432,
"name": "Coca Cola",
"size: "500ml",
"brewer": "Coke"
},
{
"product_id": 1641,
"name": "Coca Cola",
"size: "355ml",
"brewer": "Coke"
},
{
"product_id": 1010,
"name": "Pepsi",
"size": "355ml",
"brewer": "Pepsi Cola"
},
{
"product_id": 5199,
"name": "Sprite",
"size": "500ml",
"brewer": "Coke"
}
So one of those Coca Cola's should not be returned. I'm then passing that array into a component that maps through to display the data.
I cannot for the life of me figure out to filter out the duplicate names. I've tried .filter but can't figure out the logic inside, I've tried Set but that's new to me.
Anyone have any idea? Here's the call function:
getDrinks = () => {
const data = await fetch(this.state.url);
let newData= await data.json();
newData.length = 10; //the returned data is thousands long and I only want 10 displayed.
this.setState({
drinks: jsonData,
});
}
解决方案
您想跟踪在迭代时看到的名称。所以是这样的:
// A set of names that have occurred.
const names = new Set();
// Filter the data to remove duplicate names.
const result = data.filter(({ name ) => {
// If the name has occurred already, skip it.
if (names.has(name)) {
return false;
}
// Otherwise, add it the set of names and keep it.
names.add(name);
return true;
});
推荐阅读
- xamarin - 在 UI 线程上执行 MVVMCross 值转换器逻辑
- autosar - 软件集群中的诊断地址有什么用?
- ssl - 无法使用 Squid 4.8 打开一些 HTTPS
- mysql - 我们可以在 MySql 的 After_Insert 事件下创建多个触发器吗?
- django - Django 表单的内容未显示
- android - E/FirebaseInstanceId:令牌检索失败,没有异常消息。将重试令牌检索
- azure - Azure Blob 存储功能的并发问题
- javascript - 在页面内循环。在 Puppeteer 中进行评估
- c# - RabbitMQ:Fanout Exchange 当一些订阅失败时
- r - 如何循环遍历数据集