I want transform a Javascript object to a different form. Lets take an example.
may be I have an object like this,
[
{
"_id": 1,
"name": "abc",
"sub": [
"bbb",
"ccc"
]
},
{
"_id": 8,
"name": "abc1",
"sub": [
"bbb1"
]
},
{
"_id": 11,
"name": "abc"
}
]
and I want to transform that like below,
[
{
"_id": 1,
"name": "abc",
"sub": [
{
"sub": "bbb"
},
{
"sub": "ccc"
}
]
},
{
"_id": 8,
"name": "abc1",
"sub": [
{
"sub": "bbb1"
}
]
},
{
"_id": 11,
"name": "abc"
}
]
my code looks something like this,
x.map(({ sub }) => ({ sub: sub }));
If i try this, I'm getting a result something like this,
[{"sub":["bbb","ccc"]},{"sub":["bbb1"]},{}]
can anyone please help me to solve this. Thanks.
.map(el => ({...el, sub: el.sub?.map(sub => ({ sub })) || undefined }))). If you prefer to have an empty array instead ofundefinedwhen the original element has nosub, replaceundefinedwith[]