gpt4 book ai didi

javascript - 如何通过引用查找数组元素以便将数组与 typescript 合并?

转载 作者:行者123 更新时间:2023-12-03 05:28:47 24 4
gpt4 key购买 nike

我有一个对象,我想通过子对象的 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 内.

如何在 typescript 中查找对象而不是按引用而不是值?

这是我的摩卡测试用例:

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

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

最佳答案

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

这并不是说 find 不会通过引用返回对象,问题出在 concat 上。 :

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

var arr3 = arr1.concat(arr2);

关于javascript - 如何通过引用查找数组元素以便将数组与 typescript 合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com