从对象数组中获取唯一值

Get unique value from array of objects

本文关键字:唯一 获取 对象 数组      更新时间:2023-09-26

我有以下代码:

        fetchDemo(carMakesUrl).then(function(result) {
            for(var i = 0; i < result.length; i++){
                for(var prop in result[i]){
                    if(prop.length > 1){
                        console.log(result[i]['make_country']);
                    }
                }
            }
        });

和"carMakesUrl"等于"https://rawgit.com/csabapalfi/20d74eb83d0be023205225f79d3e7964/raw/7f08af5c0f8f411f0eda1a62a27b9a4ddda33397/carmakes.json"

我得到的结果是这样的:

4 Italy
4 UK
4 USA
4 Italy
8 UK
4 Germany
4 UK
4 USA
16 UK
4 Germany
8 UK
4 Italy
4 France
the list carries on..

我要找的东西是:

意大利重复了17次,这意味着"它生产17种汽车",因此其他国家将生产许多不同的汽车…

我怎样才能使console.log只输出一次国家名称和它生产的汽车数量?

fetchDemo(carMakesUrl).then(function(result) {    
  var obj = {};
  result.forEach(function(ele,ind){obj[ele.make_country] = (obj[ele.make_country] || 0) + 1});
  console.log(obj);
});

你可以这样计数

我假设obj=result。希望这对你有用。country_car_counter对象保存所需的输出

var country_car_counter = {};
      obj.map(function(item){
        var property = item.make_country;
         country_car_counter[property] = (country_car_counter[property])?country_car_counter[property] + 1 : 1 ;
      })
      console.log('this is the required object',country_car_counter)