gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:48:13 26 4
gpt4 key购买 nike

我正在尝试找出更新我的 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 } ]

最佳答案

现在很清楚你在问什么,下面应该可以解决问题:

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] 来自示例)

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

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

关于javascript - 使用 Underscore.js 映射或每个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374920/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com