Javascript映射到关联数组?

时间:2018-01-13 09:42:22

标签: javascript

我有一组像这样的对象:

Route::get('/', ['as' => '/', 'uses' => 'LoginController@getLogin']);
Route::post('/login', ['as' => 'login', 'uses' => 'LoginController@postLogin']);

Route::group(['middleware' => ['authenticates', 'checkrole']], function (){
    Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginController@getLogout']);
    Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController@dashboard']);
});

如何创建这样的关联数组?:

const content = [
    {
        title: 'Morning run',
        id: 'id1',
        desc: 'Meet at the park',
        date: '2018-01-14T09:00:00.000Z',
        location: 'Central park',
        createdBy: '23432432',
    },
    {
        title: 'Evening run',
        id: 'id2',
        desc: 'Meet by the station',
        date: '2018-01-14T18:00:00.000Z',
        location: 'Central station',
        createdBy: '23432432',
    },
];

可以使用地图功能吗?

5 个答案:

答案 0 :(得分:4)

使用array#mapObject#assign一起使用idtitle创建对象。



const content = [{ title: 'Morning run', id: 'id1', desc: 'Meet at the park', date: '2018-01-14T09:00:00.000Z', location: 'Central park', createdBy: '23432432', }, { title: 'Evening run', id: 'id2', desc: 'Meet by the station', date: '2018-01-14T18:00:00.000Z',location: 'Central station', createdBy: '23432432', }, ],
      result = Object.assign(...content.map(({id, title}) => ({[id]: title})));

console.log(result);




答案 1 :(得分:4)

由于结果中只需要一个对象,因此可以使用array#reduce,如下所示:



const content = [{
    title: 'Morning run',
    id: 'id1',
    desc: 'Meet at the park',
    date: '2018-01-14T09:00:00.000Z',
    location: 'Central park',
    createdBy: '23432432',
  },
  {
    title: 'Evening run',
    id: 'id2',
    desc: 'Meet by the station',
    date: '2018-01-14T18:00:00.000Z',
    location: 'Central station',
    createdBy: '23432432',
  },
];

var result = content.reduce(function(accum, currentVal) {
  accum[currentVal.id] = currentVal.title;
  return accum;
}, {});

console.log(result);




答案 2 :(得分:3)

使用Array.reduce这样的功能

let out = content.reduce(function(a,b){
   a[b.id] = b.title
   return a;
},{})

答案 3 :(得分:1)

const map = {};
for(const {id, title} of content)
   map[id] = title;

只需迭代您的内容并将每个条目添加到地图中。

答案 4 :(得分:0)

    let initVal = {};
    let content = [
    {
        title: 'Morning run',
        id: 'id1',
        desc: 'Meet at the park',
        date: '2018-01-14T09:00:00.000Z',
        location: 'Central park',
        createdBy: '23432432',
    },
    {
        title: 'Evening run',
        id: 'id2',
        desc: 'Meet by the station',
        date: '2018-01-14T18:00:00.000Z',
        location: 'Central station',
        createdBy: '23432432',
    },
];

    content = content.reduce(function(myObj,next) { 
        myObj[next.id] = next.title;
        return myObj; 
     }, initVal );

console.log(content);