gpt4 book ai didi

javascript - 如何根据属性值合并两个javascript数组?

转载 作者:行者123 更新时间:2023-11-28 07:29:58 24 4
gpt4 key购买 nike

我有两个数组

array1 = [{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}] 

array2 = [{"Deptid":1,"Deptname":"IT"},{"Deptid":12,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"}]

输出:

{ "0": { "id": 1, "name": "Michale Sharma", "gender": "Male", "age": 25, "salary": 10000, "Deptid": 1, "Deptname": "IT" }, "1": { "id": 2, "name": "Sunil Das", "gender": "Male", "age": 24, "salary": 5000}, "2": { "id": 3, "name": "Robin Pandey", "gender": "Male", "age": 35, "salary": 45000, "Deptid": 3, "Deptname": "HW" }, "3": { "id": 4, "name": "Mona Singh", "gender": "Female", "age": 27, "salary": 12000 }, "4" :{ "Deptid": 12, "Deptname": "HR" } } 

Image of requested output in table form

我想根据属性值合并它们,例如array1的idarray2的Deptid

这意味着如果 id 值 = 1 并且 Deptid 值 = 1,则合并记录,如果不是,则保留一个数组中的值,另一个数组将为空。换句话说,有点像 FULL OUTER JOIN 的功能。因为数组数据不可能是连续的,而且长度也可能不一样。

我已经尝试使用 Jquery.extend 如下

$.extend(true, array1,array2) 

它不接受任何属性,但会合并数组。

我还看到了this但这没有帮助。

最佳答案

看起来您需要有一个自定义逻辑。这是使用 lodash 库的示例:

var array1 = [{"id":1,"name":"Michale Sharma","gender":"Male","age":25,"salary":10000},{"id":2,"name":"Sunil Das","gender":"Male","age":24,"salary":5000},{"id":3,"name":"Robin Pandey","gender":"Male","age":35,"salary":45000},{"id":4,"name":"Mona Singh","gender":"Female","age":27,"salary":12000}] 
var array2 = [{"Deptid":1,"Deptname":"IT"},{"Deptid":12,"Deptname":"HR"},{"Deptid":3,"Deptname":"HW"}]

var defaults = {
Deptid: null,
DeptName: null
};

_.each(array1, function (obj) {
var dept = _.find(array2, { Deptid: obj.id });
_.defaults(obj, dept, defaults);
});

关于javascript - 如何根据属性值合并两个javascript数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29216813/

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