如果API调用中的项在某个键上共享相同的值,则筛选这些项



我有一个返回对象数组的数据集,我想过滤掉名称键上具有相同值的任何对象。返回数据的一个小示例:

{
"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"
}

因此,其中一个可口可乐不应该被退回。然后,我将该数组传递到一个组件中,该组件映射以显示数据。

我一辈子都想不出能过滤掉重复的名字。我试过了。filter,但找不出里面的逻辑,我试过Set,但这对我来说是新的。

有人知道吗?这是调用函数:

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

这样的东西怎么样?

const data = await fetch(this.state.url);
const jsonData = await data.json();
var filteredData = [];
jsonData.forEach(drink => {
if(!filteredData.some(x=>x.name == drink.name)){
filteredData.push(drink);
}
})

尝试使用reduce方法:

const sourceData = [{
"product_id": 574031,
"name": "Coca Cola",
'size': '500ml',
"brewer": "Coke"
},
{
"product_id": 574042,
"name": "Coca Cola",
"size": "355ml",
"brewer": "Coke"
},
{
"product_id": 7888172,
"name": "Pepsi",
"size": "355ml",
"brewer": "Pepsi Cola"
},
{
"product_id": 4359922,
"name": "Sprite",
"size": "500ml",
"brewer": "Coke"
}];
const uniqueObjects = sourceData.reduce((a, c) => {
Object.assign(a, {[c.name]: c});
return a;
}, {});
const unique = Object.values(uniqueObjects);
console.log(unique);

最新更新