Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

69
Views
Transform object in js

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!