使用reduce方法修改数组

var list=[
    { type:'a', name:'a1' },
    { type:'a', name:'a2' },
    { type:'a', name:'a3' },
    { type:'b', name:'b1' },
    { type:'b', name:'b3' },
    { type:'b', name:'b5' },
    { type:'c', name:'c9' },
];

var typedList=list.reduce((s,e)=>((s[e.type]||(s[e.type]=[])).push(e), s),{})

console.log(typedList)



{
  "a": [
    {      "type": "a",      "name": "a1"    },
    {      "type": "a",      "name": "a2"    },
    {      "type": "a",      "name": "a3"    }
  ],
  "b": [
    {      "type": "b",      "name": "b1"    },
    {      "type": "b",      "name": "b3"    },
    {      "type": "b",      "name": "b5"    }
  ],
  "c": [
    {      "type": "c",      "name": "c9"    }
  ]
}

你可能感兴趣的:(js相关方法,前端,javascript,开发语言)