首页 > 解决方案 > 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,
      });
  }

标签: javascriptarraysreactjsapifilter

解决方案


您想跟踪在迭代时看到的名称。所以是这样的:

// 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;
});

推荐阅读