因此,如果对象相等,就会有很多答案。但就我而言,仅当某些字段相等时我才希望返回,并且我无法找到任何答案。
假设我有这个对象数组:
let obj = [
{ name: 'bob', adress: 'somewhere1', country: 'sweden', nr: '1235'},
{ name: 'bob', adress: 'somewhere1', country: 'norway', nr: '7656'},
{ name: 'john', adress: 'somewhere2', country: 'denmark', nr: '54534'},
{ name: 'john', adress: 'somewhere2', country: 'US', nr: '3333'},
{ name: 'steven', adress: 'somewhere3', country: 'UK', nr: '5467'}
]
我想按名称和地址过滤它们(如果它们相等),将它们添加到新数组中:
let newObj = [
[{
name: 'bob',
adress: 'somewhere1',
country: 'sweden',
nr: '1235'
},
{
name: 'bob',
adress: 'somewhere1',
country: 'norway',
nr: '7656'
}
],
[{
name: 'john',
adress: 'somewhere2',
country: 'denmark',
nr: '54534'
},
{
name: 'john',
adress: 'somewhere2',
country: 'US',
nr: '3333'
}
],
[{
name: 'steven',
adress: 'somewhere3',
country: 'UK',
nr: '5467'
}]
]
最佳答案
const arr = [
{ name: 'bob', address: 'somewhere1', country: 'sweden', nr: '1235'},
{ name: 'bob', address: 'somewhere1', country: 'norway', nr: '7656'},
{ name: 'john', address: 'somewhere2', country: 'denmark', nr: '54534'},
{ name: 'john', address: 'somewhere2', country: 'US', nr: '3333'},
{ name: 'steven', address: 'somewhere3', country: 'UK', nr: '5467'}
];
const grouped = Object.values(arr.reduce((accum, item) => {
const nameAndAddress = `${item.name}${item.address}`;
if (!accum[nameAndAddress]) accum[nameAndAddress] = [];
accum[nameAndAddress].push(item);
return accum;
}, {}));
这将使用组合的名称和地址作为唯一标识符,并将记录分离到该标识符上的数组中,然后将这些数组从结果对象中拉出到所需输出中的数组中。
关于javascript - Typescript:仅当某些字段相等时才获取重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60640953/