I’m trying to convert an array within an array that looks like this
JavaScript
x
9
1
{
2
active:
3
[ 'Company 1' ],
4
inactive:
5
[ 'Company 2', 'Company 3'],
6
archived:
7
[ 'Company 4' ]
8
}
9
To an object that looks like this
JavaScript
1
7
1
[
2
{ state: 'active', company: 'company 1' },
3
{ state: 'inactive', company: 'company 2' },
4
{ state: 'inactive', company: 'company 3' },
5
{ state: 'archived', company: 'company 4' }
6
]
7
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
JavaScript
1
11
11
1
const obj = {
2
active: ["Company 1"],
3
inactive: ["Company 2", "Company 3"],
4
archived: ["Company 4"],
5
};
6
7
const result = Object.entries(obj).flatMap(([key, value]) =>
8
value.map((v) => ({ state: key, company: v }))
9
);
10
11
console.log(result);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }