eveo eveo - 5 months ago 9
JSON Question

Transforming an array into an object?

I'm trying to transform the following array of objects into an object that contains the label property as the key to multiple arrays of objects containing that same key as the property.

Here's a JSBin of a function that maps the array but I'm not sure about the ES6 logic I would use to get the output I want.

https://jsbin.com/foyijisaku/1/edit?js,console

original array

var originalArray =

[
{
'id': 6,
'label': 'hello'
},
{
'id': 5,
'label': 'hello'
},
{
'id': 4,
'label': 'bye'
},
{
'id': 3,
'label': 'bye'
},
{
'id': 2,
'label': 'bye'
},
{
'id': 1,
'label': 'bye'
}
]


new object

var newObject =

{
'hello': [
{
'id': 6,
'label': 'hello'
},
{
'id': 5,
'label': 'hello'
},
],
'bye': [
{
'id': 4,
'label': 'bye'
},
{
'id': 3,
'label': 'bye'
},
{
'id': 2,
'label': 'bye'
},
{
'id': 1,
'label': 'bye'
},
]
}

Answer
var originalArray =

    [
      {
        'id': 6,
        'label': 'hello'
      },
      {
        'id': 5,
        'label': 'hello'
      },
      {
        'id': 4,
        'label': 'bye'
      },
      {
        'id': 3,
        'label': 'bye'
      },
      {
        'id': 2,
        'label': 'bye'
      },
      {
        'id': 1,
        'label': 'bye'
      }
    ]

var newObject = originalArray.reduce(function(accumulator, current) {
  accumulator[current.label] = accumulator[current.label] || [];
  accumulator[current.label].push({
    id: current.id,
    label: current.label
  });
  return accumulator;
}, {})

In ES6, with spread operator:

var newObject = originalArray.reduce((accumulator, current) => {
  accumulator[current.label] = accumulator[current.label] || [];
  accumulator[current.label].push({...current});
  return accumulator;
}, {})

The reason why current is not directly pushed is to avoid keeping reference.

Comments