Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript map to Associative Array?

Tags:

javascript

I have an array of objects like so:

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

How can I create an associative array like so?:

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

Can this be done with a map function?

like image 404
Evanss Avatar asked Aug 23 '26 07:08

Evanss


1 Answers

Since you need just one object in the result, you could use array#reduce like this:

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);
like image 121
Nisarg Shah Avatar answered Aug 25 '26 19:08

Nisarg Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!