如何过滤json数组并按字母标题存储?

时间:2014-07-09 11:00:36

标签: javascript knockout.js

示例json数组:

[  { "companyName" : "Amazon",
   "assets": 35,
    "users": 3 
 },
 { "companyName" : "AT&T",
   "assets": 35,
    "users": 3 
 },
 { "companyName" : "Birla Tech",
   "assets": 35,
    "users": 3 
 },
 { "companyName" : "Capgemini",
   "assets": 35,
    "users": 3 
 }]

我希望过滤此数组并将其存储为companyName以A开头,应该在单独的'A'数组中...而且以B开头的CompanyName应该在'B'数组中。怎么做?

3 个答案:

答案 0 :(得分:0)

你要做的groupBy。看看

http://linqjs.codeplex.com/

Underscore也可以做groupby,也可能是其他库,或创建自己的。

更新:我为你推出了自己的

function groupBy(items, getKey) {
    var grouped = {};
    for(var i = 0; i < items.length; i++) {
       var key = getKey(items[i]);        
        if(grouped[key] === undefined) {
           grouped[key] = [];
        }

        grouped[key].push(items[i]);
    }

    return grouped;
};

http://jsfiddle.net/xgej2/

答案 1 :(得分:0)

创建一个对象,其中每个键都是一个字母,其中包含与该字母相关的公司信息对象数组:

var out = {};

for (var i = 0, l = arr.length; i < l; i++) {

  // get the first letter of the company name and capitalise it
  var letter = arr[i].companyName.charAt(0).toUpperCase();

  // if the letter doesn't exist in the output object create it as an array
  if (!out[letter]) { out[letter] = []; }

  // push the company object to the array
  out[letter].push(arr[i]);
}

DEMO

答案 2 :(得分:0)

希望你正在寻找这个,我理解并且我做了这个, 看看这一次,问你确切需要什么。下面是你的代码...

    my =[  { "companyName" : "Amazon",
   "assets": 35,
    "users": 3 
 },
 { "companyName" : "AT&T",
   "assets": 35,
    "users": 3 
 },
 { "companyName" : "Birla Tech",
   "assets": 35,
    "users": 3 
 },
 { "companyName" : "Capgemini",
   "assets": 35,
    "users": 3 
 }];
var result=[];
var isFound=false;
my.forEach(function(a){

    for(var j=0; j< result.length; j++){

        if(a.companyName[0]==Object.keys(result[j])[0]){
            isFound=true;
            temp=result[j];
            temp[a.companyName[0]].push(a);
        }else {
            isFound=false;
        }
    }

    if(!isFound){
        temp={};
        temp[a.companyName[0]]=[a];
        result.push(temp);
    }

});
console.log(my);