Skip to content
Advertisement

Map array of an array to an object in JavaScript [closed]

I’m trying to convert an array within an array that looks like this

{ 
  active: 
    [ 'Company 1' ],
  inactive: 
    [ 'Company 2', 'Company 3'],
  archived:
    [ 'Company 4' ]
}

To an object that looks like this

[
  { state: 'active', company: 'company 1' },
  { state: 'inactive', company: 'company 2' },
  { state: 'inactive', company: 'company 3' },
  { state: 'archived', company: 'company 4' }
]

I’m sure this isn’t to difficult, I just can’t seem to get it right. Thanks.

EDIT: I realized I wrote the question somewhat wrong. I’ve got an array within an array and I need to convert it to an object within an array. The code above is exactly how it appears in my program currently.

Sorry about the confusion. See above for this change.

Advertisement

Answer

You can easily achieve this result using flatMap and map

const obj = {
  active: ["Company 1"],
  inactive: ["Company 2", "Company 3"],
  archived: ["Company 4"],
};

const result = Object.entries(obj).flatMap(([key, value]) =>
  value.map((v) => ({ state: key, company: v }))
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement