使用 JavaScript 对所有拥有相同 '_id' 键值的具象集合进行分组
假设我们有一个类似如下这样的对象数组 −
const arr = [
{_id : "1", S : "2"},
{_id : "1", M : "4"},
{_id : "2", M : "1"},
{_id : "" , M : "1"},
{_id : "3", S : "3"}
];我们需要编写一个 JavaScript 函数,其能够获取这样的数组,并将具有相同 '_id' 键值的具象分组到一起。
因此,最终的输出应类似如下 −
const output = [
{_id : "1", M : "4", S : "2", Total: "6"},
{_id : "2", M : "1", S : "0", Total: "1"},
{_id : "6", M : "1", S : "0", Total: "1"},
{_id : "3", M : "0", S : "3", Total: "3"}
];示例
代码如下 −
const arr = [
{_id : "1", S : "2"},
{_id : "1", M : "4"},
{_id : "2", M : "1"},
{_id : "6" , M : "1"},
{_id : "3", S : "3"}
];
const pickAllConstraints = arr => {
let constraints = [];
arr.forEach(el => {
const keys = Object.keys(el);
constraints = [...constraints, ...keys];
});
return constraints.filter((el, ind) => el !== '_id' && ind === constraints.lastIndexOf(el));
};
const buildItem = (cons, el = {}, prev = {}) => {
const item = {};
let total = 0
cons.forEach(i => {
item[i] = (+el[i] || 0) + (+prev[i] || 0);
total += item[i];
});
item.total = total;
return item;
}
const buildCumulativeArray = arr => {
const constraints = pickAllConstraints(arr);
const map = {}, res = [];
arr.forEach(el => {
const { _id } = el;
if(map.hasOwnProperty(_id)){
res[map[_id] - 1] = {
_id, ...buildItem(constraints, el, res[map[_id] - 1])
};
}else{
map[_id] = res.push({
_id, ...buildItem(constraints, el)
});
}
});
return res;
};
console.log(buildCumulativeArray(arr));输出
控制台中的输出如下 −
[
{ _id: '1', M: 4, S: 2, total: 6 },
{ _id: '2', M: 1, S: 0, total: 1 },
{ _id: '6', M: 1, S: 0, total: 1 },
{ _id: '3', M: 0, S: 3, total: 3 }
]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP