唯一JSON值的数组

Array of unique JSON values

本文关键字:数组 JSON 唯一      更新时间:2023-09-26

我试图获得基于键值比较的唯一JSON数据数组。

在这个例子中,我试图删除任何具有重复category值的对象。

的例子:

 var products = [
        { category: 'fos', name: 'retek' },
        { category: 'fos', name: 'item' },
        { category: 'nyedva', name: 'blabla' },
        { category: 'fos', name: 'gihi' }
    ];
// array of hold unique values
var uniqueNames = [];
for(i = 0; i< products.length; i++){    
    if(uniqueNames.indexOf(products[i].category) === -1){
        uniqueNames.push(products[i]);        
    }        
}

我试图推到数组的任何对象,没有重复的类别值。这是一个实时的JSbin。

请帮忙!

有几种方法可以做到这一点,这是其中之一:遍历所有项目,并过滤掉我们已经添加到该类别的项目。为此,我们使用一个对象来保存我们已看到的类别和新类别,因此我们只过滤已看到的类别:

var seen = {}
var unique = products.filter(function(item){
    if(seen.hasOwnProperty(item.category)){
        return false;
    }else{
        seen[item.category] = true;
        return true;
    }
})
console.log(unique); // only 2 objects

当我尝试这样做时,我通常将所有值作为键放入映射中,因为映射数据结构只允许唯一键。在这个例子中:

var crops = [   { 
    id:     0023,
    crop:   "corn"
},
{
    id:     0034,
    crop:   "corn"
},
{
    id:     0222,
    crop:   "wheat"
}
 ];
var cropsMap = {};
for(var i = 0; i < crops.length; i++) {
   cropsMap[crops[i].crop] = true;
}
var uniqueCrops = Object.keys(cropsMap);

我做了一个codependency,如果你想看的话

lookup = [];    
for (var product, i = 0; product = products[i++];) {
   var cat = item.category;
   if (!(cat in lookup)) {
     lookup[cat] = 1;
     result.push(products[cat]);
   }
 }

Switch

for(i = 0; i< products.length; i++){    
    if(uniqueNames.indexOf(products[i].category) === -1){
        uniqueNames.push(products[i]);        
    }        
}

for(i = 0; i< products.length; i++){    
        if(uniqueNames.indexOf(products[i].category) === -1){
            uniqueNames.push(products[i].category);  // Push Name of category. Will now not place duplicates into UnqiueNames     
        }        
    }
控制台

["fos", "nyedva"]