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.
Using Array.prototype.map() twice along with the spread operator
let a = [
{
"_id": 1,
"name": "abc",
"sub": [
"bbb",
"ccc"
]
},
{
"_id": 8,
"name": "abc1",
"sub": [
"bbb1"
]
},
{
"_id": 11,
"name": "abc"
}
]
let b = a.map((el) => {
if(el.sub){
let c = el.sub.map(el2 => {
return {sub: el2}
})
el = {...el,sub: c}
}
return el;
})
console.log(b)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments