使用具有唯一字段值的Underscore JS过滤列表

时间:2016-03-07 12:01:55

标签: angularjs filter underscore.js

我有一个Object列表。我希望通过专栏获得唯一列表。 例如,我有

[
{ "city" : "Dhaka",
  "temp" : 30,
   "grade": "A"
},

{ "city" : "Comilla",
  "temp" : 32,
   "grade": "B"
},
{ "city" : "Sylhet",
  "temp" : 32,
   "grade": "A"
},
{ "city" : "Noakhali",
  "temp" : 32,
   "grade": "C"
}
]

我想在列#39; grade'

时得到
[
    { 
       "grade": "A"
    },
    { 
       "grade": "B"
    },
    { 
       "grade": "C"
    }

    ]

当我使用它时,

$scope.listOfFilterdItems = _($scope.dataList).chain().flatten().pluck('grade').unique().value();

我有一系列字符串 [" A"" B"" C"]

我不想要它。我需要对象列表。 我该怎么办?

1 个答案:

答案 0 :(得分:0)

你可以使用pick而不是采摘:

var result = _.chain(data)
    .map(function(city){
        return _.pick(city, 'grade')        
    })
    .uniq('grade')
    .value();

修改

可以更改传递给地图的功能,以便将过滤后的密钥重命名为过滤器

var gradeToFilter = function(city){
    return {
        filter: city.grade
    }
}

var result = _.chain(data)
    .map(gradeToFilter)
    .uniq('filter')
    .value();



var data = [
		{ "city" : "Dhaka",
		  "temp" : 30,
		   "grade": "A"
		},

		{ "city" : "Comilla",
		  "temp" : 32,
		   "grade": "B"
		},
		{ "city" : "Sylhet",
		  "temp" : 32,
		   "grade": "A"
		},
		{ "city" : "Noakhali",
		  "temp" : 32,
		   "grade": "C"
		}
	];


var result1 = _.chain(data)
	.map(function(city){
		return _.pick(city, 'grade')		
	})
	.uniq('grade')
	.value();
	
var gradeToFilter = function(city){
    return {
        filter: city.grade
    }
}

var result2 = _.chain(data)
    .map(gradeToFilter)
    .uniq('filter')
    .value();

document.getElementById('result1').textContent = JSON.stringify(result1);
document.getElementById('result2').textContent = JSON.stringify(result2);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>

<p>
  <pre id="result1"></pre>
</p>

<p>
  <pre id="result2"></pre>
</p>
&#13;
&#13;
&#13;