offers我有一个包含如下对象的数组:{ sellItem: { id: _, quantity: _ }, buyItem: { id: _, quantity: _ }, volume: _}我想找到重复项 - 意思是具有相同“销售 ID”和“购买 ID”的报价。我还想在原始“优惠”数组中记录这些项目的索引。我尝试这样做了 2 天,但没有成功,因为我发现很难用可管理的行数来写我想做的事情。StackOverflow 上的其他问题只涉及一个对象,而不是嵌套对象。我的offers数组的示例:{sellItem: {id: Pizza, quantity: 2}, buyItem: {id: Dollar, quantity: 1}, volume: 1}{sellItem: {id: Pizza, quantity: 3}, buyItem: {id: Dollar, quantity: 2}, volume: 1}{sellItem: {id: Banana, quantity: 2}, buyItem: {id: Pound, quantity: 1}, volume: 1}{sellItem: {id: Apple, quantity: 2}, buyItem: {id: Euro, quantity: 1}, volume: 1}{sellItem: {id: Pizza, quantity: 5}, buyItem: {id: Dollar, quantity: 3}, volume: 1}这里的预期结果是:0: Selling 2x Pizza for 1x Dollar1: Selling 3x Pizza for 2x Dollar4: Selling 5x Pizza for 3x Dollar“优惠”数组中的所有其他条目都应忽略,因为它们不是重复的优惠。
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
您可以使用filteralong withfind来搜索具有相同id.
const arr = [{sellItem: {id: 'Pizza', quantity: 2}, buyItem: {id: 'Dollar', quantity: 1}, volume: 1},
{sellItem: {id: 'Pizza', quantity: 3}, buyItem: {id: 'Dollar', quantity: 2}, volume: 1},
{sellItem: {id: 'Banana', quantity: 2}, buyItem: {id: 'Pound', quantity: 1}, volume: 1},
{sellItem: {id: 'Apple', quantity: 2}, buyItem: {id: 'Euro', quantity: 1}, volume: 1},
{sellItem: {id: 'Pizza', quantity: 5}, buyItem: {id: 'Dollar', quantity: 3}, volume: 1}];
const res = arr.filter(({sellItem: {id}},idx)=>
arr.find(({sellItem:{id:id2}},idx2) => idx !== idx2 && id === id2));
console.log(res);
添加回答
举报
0/150
提交
取消