我有一个如下的 json 文件
{"Teams": [
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
]}
提取 f3 的唯一属性值的最佳方法是什么。
在我们的示例中,我应该将唯一的 f3 属性存储在一个数组中,该数组应该具有 ["Jun-2016","May-2016","Aug-2016"]
最佳答案
使用Array#reduce
方法
var data= {"Teams": [
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Aug-2016","color":"R"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"Jun-2016","color":"G"},
{"id":"1","f1":"Currency","f2":"All","f3":"May-2016","color":"G"},
]};
var res = data.Teams.reduce(function(arr, ele) {
// check element already exist if not push the value to the array
if (arr.indexOf(ele.f3) === -1) arr.push(ele.f3);
return arr;
// set initial value as empty array
}, []);
console.log(res);
关于javascript - 唯一属性计数 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37827855/