2016-12-08 2 views
0

하위 개체의 ID로 특정 하위 요소를 평탄하게하고 병합하려는 개체가 있습니다. 중복 된 값을 가진 4 개의 객체 대신 2 개의 객체 만 가지게되므로 두 객체는 ​​병합 된 subElement 배열을 갖게됩니다. 그래서 배열을 typescript와 병합하기 위해 참조로 배열 요소를 찾는 방법은 무엇입니까?

내 인터페이스 및 테스트 케이스 이러한 :

interface ISubElement { 
    id: number; 
    price: number; 
} 

interface IElements { 
    id: number; 
    subElements: ISubElement[]; 
} 

interface IElementCollection { 
    elements: IElements[]; 
} 

const rawObject: IElementCollection = { 
    elements: [ 
     { 
      id: 1, 
      subElements: [ 
       {id: 111, price: 500}, 
      ], 
     }, 
     { 
      id: 1, 
      subElements: [ 
       {id: 222, price: 1000}, 
      ], 
     }, 
     { 
      id: 1, 
      subElements: [ 
       {id: 333, price: 1500}, 
      ], 
     }, 
     { 
      id: 2, 
      subElements: [ 
       {id: 123, price: 700}, 
      ], 
     }, 
    ], 
}; 

const expected: IElementCollection = { 
    elements: [ 
     { 
      id: 1, 
      subElements: [ 
       {id: 111, price: 500}, 
       {id: 222, price: 1000}, 
       {id: 333, price: 1500}, 
      ], 
     }, 
     { 
      id: 2, 
      subElements: [ 
       {id: 123, price: 700}, 
      ], 
     }, 
    ], 
}; 

이 내가 생각 해낸 기능은이 :

const mergeSubElements = (rawCollection: IElementCollection) => { 
    let mergedCollection: IElementCollection = <IElementCollection> { 
     elements: [], 
    }; 

    rawCollection.elements.forEach((element: IElements) => { 
     console.log('iterating', JSON.stringify(element, null, 4)); 
     const existing = mergedCollection.elements.find((existingElement: IElements) => { 
      return existingElement.id === element.id; 
     }); 

     if (existing) { 
      console.log('should add to existing', JSON.stringify(existing, null, 4)); 
      existing.subElements.concat(element.subElements); 
      return; 
     } 

     mergedCollection.elements.push(element); 
    }); 

    console.log(JSON.stringify(mergedCollection, null, 4)); 

    return mergedCollection; 
}; 

내 문제가 array.prototype.find는 값으로 나에게 개체를 얻을 것으로 보인다 참고로, 내가 concat 필드에도 불구하고 그들은 mergedCollecton 안에 있지 않을 것입니다.

값이 아닌 참조가 아닌 유형 스크립트에서 객체를 찾으려면 어떻게해야합니까?

describe('it should merge subElements for each element by id',() => { 
    it('this shall merge',() => { 

     return expect(mergeSubElements(rawObject)).to.deep.equal(expected); 
    }); 
}); 

답변

1
existing.subElements = existing.subElements.concat(element.subElements); 

그것은 그 find 참조에 의해 객체를 반환하지 않다가, 문제가 concat로했다 :

CONCAT 연() 메소드

여기 내 모카 테스트 케이스의 두 개 이상의 배열을 병합하는 데 사용됩니다. 이 메서드 은 기존 배열을 변경하지 않고 새 배열을 반환합니다.

var arr3 = arr1.concat(arr2); 
관련 문제