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);
});
});