2010-08-02 2 views
0

나는 일반적으로 같은 보이는 일부 JSON ...jquery로 JSON을 검사하여 특정 문자열의 인스턴스 수를 확인하려면 어떻게해야합니까?

{"appJSON": [ 
{ 
"title":"Application Title", 
"category":"Business", 
"industry":"Retail", 
"language":"English", 
"tags":[ 
     {"tags":"Sales"},{"tags":"Reporting"},{"tags":"Transportation"},{"tags":"Hospitality"} 
     ], 
}, 
{ 
"title":"Airline Quality Assurance", 
... 
... 
...]} 

나는 데이터의 고유 한 태그의 배열을 얻을 수 JSON 통해 반복하고 있습니다 있습니다.

내 질문에 JSON에 다른 고유 한 태그가 배열되었으므로 각 태그의 발생 횟수를 확인하는 것이 가장 좋습니다.

그래서 기본적으로 JSON에서 발견 된 모든 태그 목록을 생성하고 있습니다 (이미 갖고있는 태그).

미리 감사드립니다.

+0

Lemme guess .. tag cloud? – jessegavin

답변

2

새 태그를 찾으면 이미 태그가 있는지 확인합니다. 당신이 당신의 목록에 그것을 추가하지 않으면. 왜 당신이 뭔가를 확인 할 때.

var nextTag=//get the next tag in the JSON list 
var newTag=true; 
for(var i=0;i<tags.length;i++){ 
    if(nextTag === tags[i]){ 
    tagCount[i]++; 
    newTag=false; 
    break; 
    } 
} 
if(newTag){ 
    tags[tags.length]=nextTag; 
    tagCount[tagCount.length]=1; 
} 

이것은 tagCount[i]tags[i]에서 시간 태그의 개수가 발생 두 개의 배열을 사용한다. 이 작업을 수행하기 위해 객체를 사용할 수도 있고 싶을 수도 있습니다.

1

대안으로, 여기에 연관 배열을 채울 함수가 있습니다. 키는 태그가되고 값은 해당 태그의 발생 횟수가됩니다.

var tagCounts = []; // Global variable here, but could be an object property or any array you like really 

function countTags(tags, tagCounts) 
{ 
    $.each(tags, function(i, item) { 

     var tag = item.tags; // This would change depending on the format of your JSON 

     if(tagCounts[tag] == undefined) // If there's not an index for this tag 
      tagCounts[tag] = 0; 

     tagCounts[tag]++; 

    }); 
} 

그래서 당신은 (합계) 배열하여 tagCounts 전달, 태그의 배열의 수에이 함수를 호출 할 수 있고, 합계를 집계합니다.

다음
var tags1 = [{"tags":"Sales"},{"tags":"Reporting"},{"tags":"Transportation"},{"tags":"Hospitality"}]; 
var tags2 = [{"tags":"Reporting"},{"tags":"Transportation"}]; 
var tags3 = [{"tags":"Reporting"},{"tags":"Hospitality"}]; 

countTags(tags1, tagCounts); 
countTags(tags2, tagCounts); 
countTags(tags3, tagCounts); 

당신과 같이 그들을 읽을 수 있습니다

for(var t in tagCounts) 
    // t will be the tag, tagCounts[t] will be the number of occurrences 

작업을 예를 여기에 : http://jsfiddle.net/UVUrJ/1/

qw3n의 대답은 실제로 일을 더 효율적인 방법입니다, 당신은 단지 반복하고로 모든 태그를 한 번 훑어 볼 수 있습니다.하지만 실제로 JSON 소스가 없다면 그 차이는 눈에 띄지 않을 것입니다.

관련 문제