Javascript数组到对象转换

时间:2018-05-07 20:44:44

标签: javascript arrays angular typescript

请告知我们如何将下面的对象数组转换为使用typescript / java脚本指定的对象:

[
  {
    "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
      }
    ]
  }
]

要:

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

];

请使用spread运算符或任何其他方法帮助转换对象。谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用.map().reduce()方法:

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; }