查找数组中对象的副本



嗨,我有一个对象数组,我想找到一个对象匹配另一个对象,问题是我有一个对象数组在对象中我不想直接比较它因为有一个对象属性无关紧要下面是一个示例对象:

[{
name: 'name',
price: 50,
amount: 1,
products: [{
amount: 1,
variant: 'first variant',
name: 'product one'
},
{
amount: 3,
variant: 'first variant',
name: 'product two'
}
]
},
{
name: 'second name',
price: 30,
amount: 1,
products: [{
amount: 1,
variant: 'first variant',
name: 'product three'
},
{
amount: 3,
variant: 'first variant',
name: 'product two'
}
]
}
]

这是第二个对象:

{
name: 'second name',
price: 30,
amount: 1,
products: [{
amount: 1,
variant: 'first variant',
name: 'product three'
},
{
amount: 3,
variant: 'first variant',
name: 'product two'
}
]
}

我想检查第一个数组是否包含确切的对象减去产品对象的数量,我如何检查这个并获得返回的对象实例?

这是一个不寻常但有效的解决方案,我在字符串中转换对象,消除products数组内对象的amount属性并比较它们。

const arrayOfObjects = [{
name: 'name',
price: 50,
amount: 1,
products: [{
amount: 1,
variant: 'first variant',
name: 'product one'
},
{
amount: 3,
variant: 'first variant',
name: 'product two'
}
]
},
{
name: 'second name',
price: 30,
amount: 1,
products: [{
amount: 1,
variant: 'first variant',
name: 'product three'
},
{
amount: 3,
variant: 'first variant',
name: 'product two'
}
]
}
]
const objToBeFound = {
name: 'second name',
price: 30,
amount: 1,
products: [{
amount: 1,
variant: 'first variant',
name: 'product three'
},
{
amount: 3,
variant: 'first variant',
name: 'product two'
}
]
}
const match = arrayOfObjects.find((obj) => JSON.stringify(obj).replaceAll(/{"amount":d+,/g, '{') === JSON.stringify(objToBeFound).replace(/{"amount":d+,/g, '{'));
console.log(match)

最新更新