JavaScriptの「_id」キーの値が同じであるすべてのオブジェクトをグループ化します
このようなオブジェクトの配列があるとします-
const arr = [
{_id : "1", S : "2"},
{_id : "1", M : "4"},
{_id : "2", M : "1"},
{_id : "" , M : "1"},
{_id : "3", S : "3"}
]; このような配列を1つ取り込んで、「_id」キーの値が同じであるすべてのオブジェクトをグループ化するJavaScript関数を作成する必要があります。
したがって、最終的な出力は次のようになります-
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 }
] -
JavaScriptの値に基づいてオブジェクトをグループ化する方法は?
以下は、JavaScriptの値に基づいてオブジェクトをグループ化するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
-
JavaScriptのオブジェクトにreduceメソッドを適用するにはどうすればよいですか?
以下は、JavaScriptのオブジェクトにreduceメソッドを適用するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <sty