-1

I get an array of objects:

const inputStructure = [
  {
    state: 'LA',
    insurance: 'Test1'
  },
  {
    state: 'LA',
    insurance: 'Test2'
  },
  {
    state: 'TX',
    insurance: 'Test3'
  }
]

How can I group objects with the same state property? I need to create a function which would return the following result:

const outputStructure = {
  'LA': {
    state: 'LA',
    insurances: ['Test1', 'Test2']
  },
  'TX': {
    state: 'TX',
    insurances: ['Test3']
  }
}
Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
dev_jun
  • 185
  • 1
  • 7
  • 1
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Aug 24 '21 at 23:38
  • Have you looked at the `map` or `reduce` functions? These methods will help you iterate over the structure and create the new structure that you want. – Kostas Minaidis Aug 24 '21 at 23:39
  • Voted to close as a duplicate. Many libraries have a `groupBy` function, and it's easy to write your own as seen in the duplicate. – Scott Sauyet Aug 25 '21 at 12:38

2 Answers2

2

You can use:

const inputStructure = [
  {
    state: 'LA',
    insurance: 'Test1'
  },
  {
    state: 'LA',
    insurance: 'Test2'
  },
  {
    state: 'TX',
    insurance: 'Test3'
  }
];

const data = {};

for (const item of inputStructure) {
  if (!data[item.state]) {
    data[item.state] = {
      state: item.state,
      insurances: []
    }
  }
  data[item.state].insurances.push(item.insurance);
}

console.log(data);
Amir MB
  • 3,233
  • 2
  • 10
  • 16
1

You can use the reduce array method to achieve it:

const inputStructure = [{
    state: 'LA',
    insurance: 'Test1'
  },
  {
    state: 'LA',
    insurance: 'Test2'
  },
  {
    state: 'TX',
    insurance: 'Test3'
  }
]

const output = inputStructure.reduce((acc, e) => {
  acc[e.state] = ({
    state: e.state,
    insurances: (acc[e.state]?.insurances || []).concat(e.insurance)
  });
  return acc;
}, {})

console.log(output)
AlexSp3
  • 2,201
  • 2
  • 7
  • 24