2017-12-21 23 views
0

array에 삽입하기 전에 여러 필드가 중복되었는지 확인하려고 할 때 몇 가지 문제가있었습니다. 내가하려고하는 것은 firebase에서 검색하고 array에 삽입하기 전에 accountIDsubtype 필드를 확인한 후 Promise로 해결합니다.배열에 삽입하기 전에 Javascript 검사가 중복되었습니다.

내가 무엇을하려고하면 같은 accountID, 다른 subtype 다음 추가 할 경우; 동일한 accountID, 동일 subtype 인 경우, 다음으로 이동합니다. 다른 경우 accountID, 다른 subtype을 추가합니다. 여기 내 코드입니다 :

코드 :

var datasetarr = []; 
let promiseKey = new Promise((resolve, reject) => { 
       for(var i = 0; i < receiptlist.length; i++){ 
        for(var k = 0; k < ritemlist.length; k++){ 
         if(receiptlist[i].date.substring(0, 4) == new Date().getFullYear()){ 
          if(ritemlist[k].receiptID == receiptlist[i].receiptID){ 
           //check duplicate here before insert 
           if (!datasetarr.find(o => o.accountID === receiptlist[i].accountID && o.subtype === ritemlist[k].type)) 
            datasetarr.push({accountID: receiptlist[i].accountID, subtype: ritemlist[k].type}); 
           } 
          } 
         } 
        } 
       } 
      resolve(datasetarr); 
      }); 

내가 배열을 인쇄하려고 부분 :

배열 :

promiseKey.then((arr) => { 
      console.log(arr); 
}); 

내가 출력 점점 :

출력 :

enter image description here

나는 여전히 같은 accountID가와 같은 하위 유형과 중복을 많이 참조하십시오. 이 문제를 해결할 수있는 방법이 있습니까?

감사합니다.

+0

당신이 _.some (['lodash을 사용할 수 있습니다 – zabusa

+1

[JSON Array에서 중복 객체 제거] (https://stackoverflow.com/questions/)의 복제본이있을 수 있습니다. { "a : 1}, {"b ": 2} 23507853/remove-duplicate-objects-from-json-array) –

+1

입력 데이터의 예 없이는 도움이되지 않습니다. –

답변

1

find return undefined 데이터가없는 경우; 그래서 당신이해야 할 일은 반환 된 값이 undefined 여부를 확인하는 것입니다 그리고 당신은 당신의 계산

var found = datasetarr.find(o => o.accountID === receiptlist[i].accountID && o.subtype === ritemlist[k].type) 
    if (found === undefined){ 
     //do computation 
    } 
+0

아니요 ritemlist [k] .type이 정확합니다! – hyperfkcb

+0

@hyperfkcb 무엇이 입력되어 있습니까? – edkeveked

+0

스크린 샷의 데이터! 예를 들어 첫 번째 accountID에 다음과 같이 eyecare, eyecare, eyecare가 있습니다. .. – hyperfkcb

0

당신은 배열을 처리하기위한 아주 좋은 라이브러리 인 lodash을 사용할 수 있습니다 않습니다. 귀하의 경우 데이터에

이 계정 아이디에 의해 고유해야하고 데이터가 데이터 변수에 저장되고,이 같은 _.uniqBy() 함수를 사용할 수 있습니다

jvar datasetarr = []; 
    let promiseKey = new Promise((resolve, reject) => { 
      for(var i = 0; i < receiptlist.length; i++){ 
       for(var k = 0; k < ritemlist.length; k++){ 
        if(receiptlist[i].date.substring(0, 4) == new 
         Date().getFullYear()){ 
         if(ritemlist[k].receiptID == receiptlist[i].receiptID){ 
            //Push your object here. 
           datasetarr.push({accountID: receiptlist[i].accountID, subtype: ritemlist[k].type}); 
          } 
         } 
        } 
       } 
      } 

      //Before resolving check for the duplicates. 
      _.uniqBy(datasetarr, function (data) { 
       return data.accountID; 
      }); 

      resolve(datasetarr); 
     }); 
+0

정말 고마워요! – hyperfkcb