Uffo
Uffo

Reputation: 10046

TypeScript associative array

So I'm trying to group some reservations by business id. I'm looking for an end result like this:

[ [businessID1] => [Object1,Object2, Object3], [businessID2] => [Object1,Object2], [businessID3] => [Object1,Object2] ]

My current code:

let groups = new Array;
this.reservations.map(function (value) {
  groups[value.businessID] = value;
});

So right now it doesn't work... because each time it's going to re-write that array key. I'm new to the typescript/js world, any help is appreciated.

Upvotes: 1

Views: 6252

Answers (1)

janos
janos

Reputation: 124666

If the value does not exist, create an empty array, and append the value to it with push:

if (groups[value.businessID] === undefined) {
  groups[value.businessID] = [];
}
groups[value.businessID].push(value);

Or more compactly:

(groups[value.businessID] = groups[value.businessID] || []).push(value);

Upvotes: 2

Related Questions