繁体   English   中英

Javascript映射到关联数组?

[英]Javascript map to Associative Array?

我有一个像这样的对象数组:

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',
    },
];

我如何像这样创建一个关联数组?:

const output = {'id1' : 'Morning run', 'id2' : 'Evening run'}

可以使用地图功能来完成吗?

使用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); 

由于结果中只需要一个对象,因此可以使用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); 

像这样使用Array.reduce函数

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

只需遍历您的内容并将每个条目添加到地图即可。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM