Henrik Maaland
Henrik Maaland

Reputation: 230

Mapping array with one key and multiple values to new object with instances of same value in new object

This is what i have now which returns an array with all objects like Whole Object below:

let unique = getFromDb().then(values => values.map(value => value))

Whole object:

0:
blob: Blob {size: 21481, type: "image/png"}
group: "2020-10-06T07:51:18.816Z"
key: "https://opencache.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=topo4&zoom=19&x=270507&y=155468"
timestamp: "2020-10-6 9:51:18"
url: "https://opencache3.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=topo4&zoom=19&x=270507&y=155468"
urlTemplate: "https://{s}.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=topo4&zoom={z}&x={x}&y={y}"
x: 270507
y: 155468
z: 19

How can i map group to a new array with all values that has same group value? for example: 0: group: 'foo' 1: group: 'foo' 2: group: 'bar'

should be: mappedArr = group[{'foo', 'foo'}, {'bar'}) the important thing is that i have access to the properties from the whole object when calling the mappedArr

It will be used like this:

Group: foo

Group: bar

Upvotes: 0

Views: 626

Answers (1)

MauriceNino
MauriceNino

Reputation: 6757

You can just reduce it like so:

const data = [{
  group: "foo",
  url: "url 1"
}, {
  group: "foo",
  url: "url 2"
},{
  group: "bar",
  url: "url 3"
},{
  group: "foo",
  url: "url 4"
}];

const groupArr = (arr) => {
  return Object.values( // get array from all the values
    arr.reduce((acc, el) => { // reduce to an object with the group as keys and the single items as value array
      if(acc[el.group] == null)
         acc[el.group] = [el];
      else
         acc[el.group].push(el);

      return acc;
    }, {})
  )
}

console.log(groupArr(data));

Upvotes: 1

Related Questions