当每个数组中的id具有不同类型(字符串,数字)时合并两个数组(Merge two arrays when id in each array is of different type (string,

编程入门 行业动态 更新时间:2024-10-21 19:34:15
当每个数组中的id具有不同类型(字符串,数字)时合并两个数组(Merge two arrays when id in each array is of different type (string, number))

使用lodash,当一个数组的id为字符串时,如何通过比较id来合并两个数组,另一个数组的id是否为数字?

var a = [{ id: 1, item: 1 }, { id: 2, item: 2 }, { id: 3, item: 4 }]; var b = [{ id: "1", profile: 1 }, { id: "2", profile: 2 }];

这就是我的尝试。 如果两个数组中的ID都是字符串或两个ID都是数字,则此方法可以正常工作。 添加toString()或parseInt似乎也不起作用。

return _.map(a, function(obj) { return _.assign(obj, _.find(b, { id: obj.id })); });

Using lodash, how can I merge two arrays by comparing ids when one array has the id as a string, and the other has the id as a number?

var a = [{ id: 1, item: 1 }, { id: 2, item: 2 }, { id: 3, item: 4 }]; var b = [{ id: "1", profile: 1 }, { id: "2", profile: 2 }];

This is what I have tried. This works fine if the ids in both arrays are strings or both ids are numbers. Adding toString() or parseInt doesn't seem to work either.

return _.map(a, function(obj) { return _.assign(obj, _.find(b, { id: obj.id })); });

最满意答案

如何将自定义函数传递给_.find()方法?

return _.map(a, function(obj) { return _.assign(obj, _.find(b, function(o) { return o.id == obj.id; })); });

How about passing a custom function to the _.find() method?

return _.map(a, function(obj) { return _.assign(obj, _.find(b, function(o) { return o.id == obj.id; })); });

更多推荐

本文发布于:2023-07-16 12:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   不同类型   组中   个数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!