0

Please advice on how can we convert the below array of objects into an object of specified using typescript/java script:

[
  {
    "name": "Alex",
    "edu": [
      {
        "degree": "Grad",
        "year": 2007
      },
      {
        "degree": "Undergrad",
        "year": 2005
      }
    ]
  },
  {
    "name": "Ali",
    "edu": [
      {
        "degree": "Grad",
        "year": 2010
      },
      {
        "degree": "UnderGrad",
        "year": 2008
      }
    ]
  },
  {
    "name": "Nik",
    "edu": [
      {
        "degree": "Grad",
        "year": 2009
      },
      {
        "degree": "UnderGrad",
        "year": 2007
      }
    ]
  }
]

To:

[   { name: "Alex", Grad: 2007, Undergrad: 2005 },
    { name: "Ali", Grad: 2010, Undergrad: 2008 },
    { name: "Nik", Grad: 2009, Undergrad: 2007 }

];

Please help to convert the object using spread operator or any other. Thank you !

1 Answer 1

4

You can use .map() and .reduce() methods:

let data = [{"name": "Alex","edu": [{"degree": "PhD","year": 2012},{"degree": "Grad","year": 2007},{"degree": "Undergrad","year": 2005}]},{"name": "Ali","edu": [{"degree": "Masters","year": 2012},{"degree": "Grad","year": 2010}]},{"name": "Nik","edu": [{"degree": "Masters","year": 2011},{"degree": "Grad","year": 2009}]}];

let result = data.map(
               o => Object.assign(
                 {name: o['name']},
                 o['edu'].reduce((a, c) => (a[c['degree']] = c['year'], a), {})
               )
             );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

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.