Search code examples
javascriptlodash

Map collection to object


How to map a collection (array of objects) to object with key and value from the collection objects members? The collection is:

const collection = [{
  id: 1,
  url: 'http://url1.com'
}, {
  id: 2,
  url: 'http://url2.com'
}, {
  id: 3,
  url: 'http://url3.com'
}];

The result should be:

{
  1: 'http://url1.com',
  2: 'http://url2.com',
  3: 'http://url3.com'
}

Would be better to use lodash for this


Solution

  • The simplest way is to loop through the collection array and add new key-value pair to an object like this:

    const collection=[{id:1,url:'http://url1.com'},{id:2,url:'http://url2.com'},{id:3,url:'http://url3.com'}];
    
    const ouptut = {};
    for (const o of collection)
      ouptut[o.id] = o.url
    
    console.log(ouptut)

    Another approach is to use map to create a 2D array of entries like this:

    [ [1,"http://url1.com"], [2,"http://url2.com"], [3,"http://url3.com"]]
    

    Then use Object.fromEntries() to create an object from these entries

    const collection=[{id:1,url:'http://url1.com'},{id:2,url:'http://url2.com'},{id:3,url:'http://url3.com'}];
    
    const ouptut = Object.fromEntries(collection.map(o => [o.id, o.url]))
    
    console.log(ouptut)