cphill
cphill

Reputation: 5924

Map or Each for Values with Underscore.js

I am trying to figure out the best way to update my underscore.js .map method since the inclusion of a new field value that should be grouped with the current value being passed to .map. Should I use .map or .each with the new update and should I store the values as an object or object in an array and pass that to the .map or .each to achieve my desired outcome? At the moment I tried the object approach with .map, but the values are coming through as arrays.

Proper format:

[ { reportTitle: 'Title1', reportLink: 'test.com', id: 166 },
  { reportTitle: 'Title2', reportLink: 'test2.com', id: 166 } ]

Original (Working):

var links = _.map(req.body.reportLink, function(link){
                    return {
                        reportLink: link,
                        id: blog.id
                    };
                });

Output:

[ { reportLink: 'test.com', id: 166 },
  { reportLink: 'test2.com', id: 166 } ]

Updated (Not Working):

var linkAttributes = { title: req.body.reportTitle, link: req.body.reportLink}
var links = _.map(linkAttributes, function(link) {
  return {
      reportTitle: link.title,
      reportLink: link.link,
      id: blog.id
  };

});

Output:

[ { reportTitle: [ 'Test 1', 'Test 2' ],
    reportLink: [ 'test1.com', 'test2.com' ],
    id: 164 } ]

Upvotes: 2

Views: 101

Answers (2)

HMR
HMR

Reputation: 39340

It is now clear what it is you're asking, the following should do the trick:

const zip = (arr1, arr2) =>
  [...new Array(Math.max(arr1.length, arr2.length))].map(
    (_, i) => [arr1[i], arr2[i]],
  );

const reportTitle = ['test-title', 'test-title2'];
const reportLink = ['test.com', 'test2.com'];
console.log(
  zip(reportTitle, reportLink).map(
    ([reportTitle, reportLink]) => ({
      reportTitle,
      reportLink,
      id: 166,
    }),
  ),
);

The zip utility takes 2 arrays (for example [1,2,3] and [5,6,7]) and returns an array with an element from each array: ([[1,5],[2,6],[3,7] from the example)

Then it maps over this array to create an array of objects.

The function passed to map uses destructuring parameters to quickly name the 2 elements from the array passed to the map function.

Upvotes: 2

аlex
аlex

Reputation: 5698

_.map -> shoud have first argument as array

var linkAttributes = [
                       { 
                         title: req.body.reportTitle, 
                         link: req.body.reportLink
                        }
                     ]; // shoud be array
var links = _.map(linkAttributes, function(link) {
  return {
      reportTitle: link.title,
      reportLink: link.link,
      id: blog.id
  };

Upvotes: 0

Related Questions