【发布时间】:2024-01-12 09:18:01
【问题描述】:
我有一个对象,我想通过子对象的 id 展开并合并某些子元素。这样我就只有两个,而不是 4 个具有重复值的对象,然后这两个将有一个合并的 subElement 数组。
所以这些我的接口和测试用例:
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 内。
如何在打字稿中找到对象而不是按引用而不是值?
这是我的 mocha 测试用例:
describe('it should merge subElements for each element by id', () => {
it('this shall merge', () => {
return expect(mergeSubElements(rawObject)).to.deep.equal(expected);
});
});
【问题讨论】:
标签: javascript arrays typescript find concat