-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']
  }
}
3
  • 1
    Familiarize yourself with how to access and process nested objects, arrays or JSON and how to create objects and use the available static and instance methods of Object and Array. Commented Aug 24, 2021 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. Commented Aug 24, 2021 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. Commented Aug 25, 2021 at 12:38

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.