我需要遍历对象数组,并对 unique _id的总数求和。想象一下这样的数据结构:
[
{ firstName: "John",
lastName: "Johnson",
_id: 23
},
{ firstName: "John",
lastName: "Johnson",
_id: 23
},
{ firstName: "Mary",
lastName: "Smith",
_id: 24
}
]
...对于上述数据集,我的totalUniqueIDs
应该是2
。
如果我只是遍历一个数组并获得“ _id”的和,我会这样做:
let customersArray = docs.map(doc => doc._id);
let customersArrayLength = customersArray.length
console.log(customersArrayLength); // 3
这当然会给我3个结果。
在这种情况下,我怎样才能得到 unique _id的总和?我是否首先将array
转换为set
,然后找到length
或size
?
答案 0 :(得分:3)
您可以使用.map()
来获取ids
的数组,并使用Set对其进行重复数据删除:
const data = [{
firstName: "John",
lastName: "Johnson",
_id: 23
},
{
firstName: "John",
lastName: "Johnson",
_id: 23
},
{
firstName: "Mary",
lastName: "Smith",
_id: 24
}
]
const result = [... new Set(data.map(({_id}) => _id))]
console.log(result.length)
答案 1 :(得分:3)
另一种选择是使用reduce
,以_id作为键将数组汇总为一个对象。使用Object.values
将对象转换回数组。
var arr = [{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"Mary","lastName":"Smith","_id":24}]
var result = Object.values(arr.reduce((c, v) => Object.assign(c, {[v._id]:v}), {}));
console.log(result.length);
另一种选择是使用new Set
和size
属性
var arr = [{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"John","lastName":"Johnson","_id":23},{"firstName":"Mary","lastName":"Smith","_id":24}]
var result = new Set(arr.map(o => o._id)).size;
console.log(result);
答案 2 :(得分:1)
使用map()从对象数组中获取所有_id
,并使用Set查找唯一的_id
,最后使用size
来获取多少id是唯一的吗?
设置对象可让您存储任何类型的唯一值
map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数
var obj = [{
"firstName": "John",
"lastName": "Johnson",
"_id": 23
},
{
"firstName": "John",
"lastName": "Johnson",
"_id": 23
},
{
"firstName": "Mary",
"lastName": "Smith",
"_id": 24
}
];
function countUnique(iterable) {
return new Set(iterable).size;
}
finalArray = obj.map(function(obj) {
return obj._id;
});
console.log(countUnique(finalArray));