JavaScriptでJSONオブジェクトを2つのプロパティでグループ化してカウントする方法
次のようなオブジェクトの配列があるとします。
const arr = [
{"location":"Kirrawee","identity_long":"student"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"visitor"},
{"location":"Kirrawee","identity_long":"worker"},
{"location":"Sutherland","identity_long":"student"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Sutherland","identity_long":"worker"},
{"location":"Sutherland","identity_long":"resident"},
{"location":"Miranda","identity_long":"resident"},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"student"},
{"location":"Miranda","identity_long":""},
{"location":"Miranda","identity_long":"worker"},
{"location":"Miranda","identity_long":"resident"}
];このようなオブジェクトの配列を受け取るJavaScript関数を作成する必要があります。この関数は、locationプロパティとidentityプロパティの組み合わせを基準に、同一のオブジェクトをすべてグループ化した新しい配列を作成します。
さらに、各オブジェクトには、元の配列内で出現した回数を表すcountプロパティを割り当てます。
したがって、上記の配列に対する出力は次のようになります。
const output = [
{"location":"Kirrawee","identity":"student","count":1},
{"location":"Kirrawee","identity":"visitor","count":2},
{"location":"Kirrawee","identity":"worker","count":1},
{"location":"Sutherland","identity":"student","count":1},
{"location":"Sutherland","identity":"resident","count":2},
{"location":"Sutherland","identity":"worker","count":1},
{"location":"Miranda","identity":"resident","count":2},
{"location":"Miranda","identity":"worker","count":2},
{"location":"Miranda","identity":"student","count":1}
];実装例
コードは以下のとおりです。
const groupArray = (arr = []) => {
// Mapを作成
let map = new Map()
for (let i = 0; i < arr.length; i++) {
const s = JSON.stringify(arr[i]);
if (!map.has(s)) {
map.set(s, {
location: arr[i].location,
identity: arr[i].identity_long,
count: 1,
});
} else {
map.get(s).count++;
}
}
const res = Array.from(map.values())
return res;
};
console.log(groupArray(arr));コードの解説
このコードの仕組みを簡単に説明します。
- JSON.stringify()で各オブジェクトを文字列化し、それをMapのキーとして使用します。これにより、オブジェクト同士を簡単に比較・識別できます。
- Mapに同じキーが存在しない場合は、locationとidentityの値を格納した新しいオブジェクトをcount: 1で登録します。
- 同じキーがすでに存在する場合は、該当オブジェクトのcountを1ずつ増やします。
- 最後にArray.from(map.values())でMapの値を配列に変換して返します。
なお、元の配列には空文字列のidentity_longが含まれていますが、この場合も1つのグループとしてカウントされる点に注意してください。
出力結果
コンソールには次のように出力されます。
[
{ location: 'Kirrawee', identity: 'student', count: 1 },
{ location: 'Kirrawee', identity: 'visitor', count: 2 },
{ location: 'Kirrawee', identity: 'worker', count: 1 },
{ location: 'Sutherland', identity: 'student', count: 1 },
{ location: 'Sutherland', identity: 'resident', count: 2 },
{ location: 'Sutherland', identity: 'worker', count: 1 },
{ location: 'Miranda', identity: 'resident', count: 2 },
{ location: 'Miranda', identity: 'worker', count: 2 },
{ location: 'Miranda', identity: 'student', count: 1 },
{ location: 'Miranda', identity: '', count: 1 }
]この手法を使えば、複数のプロパティを持つオブジェクトの配列を効率的にグループ化し、集計することができます。データの集計やレポート生成など、さまざまな場面で活用できる汎用的なパターンです。
-
JavaScriptでオブジェクトを作成し、プロパティにアクセスする方法を徹底解説
JavaScriptでは、オブジェクトリテラル(波括弧 {})を使うことで、キーと値のペアを持つオブジェクトを簡単に作成できます。作成したオブジェクトのプロパティには、ドット記法(obj.propertyName)やブラケット記法(obj[propertyName])でアクセスします。 以下は、JavaScriptでオブジェクトを作成し、そのプロパティやメソッドにアクセスする具体的なコード例です。 コード例 <!DOCTYPE html> <html lang=ja> <head> <meta charset=UTF-8 /> <meta
-
JavaScriptで既存のオブジェクトにプロパティとメソッドを追加する方法
JavaScriptのオブジェクトは動的な性質を持っており、一度作成した後でも、いつでも新しいプロパティやメソッドを追加できます。最もシンプルな方法は、ドット記法(オブジェクト名.プロパティ名)を使って値を代入することです。プロパティに関数を代入すれば、それがそのままメソッドとして機能します。 基本的な書き方 object.newProperty = value; object.newMethod = function() { // 処理 }; サンプルコード 以下は、既存の student オブジェクトにプロパティとメソッドを追加し、その内容を画面に表示する完全な例で