当每个数组中的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; })); });更多推荐
发布评论