2015-01-24 9 views
1

주요 개체에서 결합 프로세스 배열 :자바 스크립트 - 얻을 나는 다음과 같은 구조의 객체가

나는이 개체에서 모든 "postTags"배열에서 모든 값을 얻을 필요가
var PostsData = [ 
       { 
        postId: 1, 
        postTitle: 'Cuba slam U.S. on human rights', 
        postExcerpt: 'Washington (CNN)U.S. and Cuban officials began a historic round of talks on Wednesday to bridge a 50-year rift in diplomatic relations, but just a day later, the Cuban delegation slammed the United States on its human rights track record.', 
        postTags: ['cuba', 'human rights', 'diplomatics', 'world'] 
       }, 
       { 
        postId: 2, 
        postTitle: 'YouTube stars interview Obama', 
        postExcerpt: "In his continuing effort to connect to a younger audience (like the time he went on 'Between Two Ferns'), President Barack Obama sat down with, and took questions, from three YouTube stars: GloZell Green (3 million followers), Bethany Mota (8 million followers) and half of the vlogbrothers (2.4 million followers).", 
        postTags: ['YouTube', 'interview', 'Obama', 'president'] 
       }, 
       // etc... 
      ]; 

(결합을 모든 배열) 및 그 이후에 나는 그것에서 모든 반복 값을 제거해야합니다. 따라서 반복되지 않는 값으로 모든 태그를 한 번에 추출해야합니다. 나는 루프를 파고 있지만 매우 복잡해지고 어떤 점에서 내 지식이 부족합니다. 그것에 대해 제안 해 주시겠습니까? 미리 감사드립니다.

(. 내가 AngularJS와 환경에서 사용하고 내가 중첩 NG-반복을 시도하고 있었고, 난 내가 뭔가 쉽게하지만 행운과 함께 올 것이다 희망)

답변

0

jQuery를 사용하여 (필요에 따라 다른 문법을 적용) 당신이 undersc 사용할 수 있는지,

var uniqueTags = PostsData.reduce(function(allTags, post) { 
    post.postTags.forEach(function(tag) { 
    if(allPosts.indexOf(tag) === - 1) { 
     allTags.push(tag) 
    } 
    }); 
    return allTags; 
}, []); 

또는 : 당신은 고유의 태그 값의 배열을 구축 Array.prototype.reduceArray.protoype.forEach을 사용할 수

var containerObject = {}, 
    finalArray = new Array(); 
$.each(PostsData, function(key, value) { 
    $.each(value.postTags, function(key, value){ 
     containerObject[value] = true 
    }); 
}); 
$.each(containerObject, function(key, value) { 
    finalArray.push(key) 
}); 
+0

와우! 마술처럼 작동합니다! 방금 테스트되었습니다. 고마워요! 이제 나는 그것에 대해 잠시 묵상하고 무슨 일이 일어나고 어떻게 태그가 finalArray에서 반복되지 않는지를 알아야합니다. 조금 번역 할 수 있습니까? :) –

+2

실제로 jQuery를 사용할 필요가 없습니다. 이 작업을 수행하기 위해 jQuery를 앱의 취약성으로 추가하지 마십시오. 네이티브 JavaScript는 ('$ .each' 대신에'Array.prototype.forEach'를 사용하는 것만으로) 잘 할 것입니다. – joews

+1

예. 각 태그는 컨테이너 객체의 속성으로 매핑됩니다. 반복 값이 있으면 새 속성을 추가하는 대신 기존 속성의 값을 변경하기 만하면됩니다. 그런 다음 컨테이너 객체의 속성을 나열하고 최종 배열로 밀어 넣습니다. –

2

ore.js 또는 lo-dash :

_.chain(PostsData).pluck('postTags').flatten().uniq().value() 
+0

감사합니다! 당신이 쓴 글은 너무 복잡해 보이지 않습니다! :) 나는이 감소 방법에 대해 몰랐다. 고마워요! 그것은 작동하고 그것은 정확히 내가 필요로하는 것입니다! –

관련 문제