1

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.

3
  • 1
    what have you tried so far Commented Jan 13, 2022 at 12:00
  • added along with the question body. Commented Jan 13, 2022 at 12:02
  • 1
    .map(el => ({...el, sub: el.sub?.map(sub => ({ sub })) || undefined }))). If you prefer to have an empty array instead of undefined when the original element has no sub, replace undefined with [] Commented Jan 13, 2022 at 12:11

1 Answer 1

2

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)

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

1 Comment

Oh hell yeah, it worked. Thanks a ton,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.