使用Underscore.js映射值或每个值

时间:2018-11-19 12:43:50

标签: javascript underscore.js

我正在尝试找出更新我的underscore.js .map方法的最佳方法,因为其中包含一个新字段值,该字段值应与传递给.map的当前值分组。我应该在新的更新中使用.map.each还是将值存储为数组中的对象或对象并将其传递给.map.each来实现我想要的结果?目前,我尝试使用.map进行对象方法,但是这些值以数组形式通过。

正确的格式:

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

原始(工作中):

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

输出:

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

已更新(无效):

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

});

输出:

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

2 个答案:

答案 0 :(得分:2)

现在很清楚您要问的是什么,以下方法可以解决问题:

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

zip实用程序采用2个数组(例如[1,2,3]和[5,6,7]),并返回一个数组,其中包含每个数组中的元素:(示例中的[[1,5],[2,6],[3,7])< / p>

然后在该数组上maps创建一个对象数组。

传递给map的函数使用destructuring parameters快速命名传递给map函数的数组中的2个元素。

答案 1 :(得分:0)

_.map->应该将第一个参数设为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
  };