我有两个数组,比如
var array1 = [{group_name: "Gp HQ, Hyderabad", group_id: "1"},
{group_name: "Gp HQ, Secunderabad", group_id: "2"},
{group_name: "Group HQ, Guntur", group_id: "3"}];
var array2 = [
{unit_total: 1, branch_name: "1 (T) Air Sqn", branch_group_id: "1", branch_id: "6"},
{unit_total: 1, branch_name: "1 (T) Arty Bty", branch_group_id: "1", branch_id: "5"},
{unit_total: 3, branch_name: "1 (T) Bn", branch_group_id: "1", branch_id: "1"},
{unit_total: 1, branch_name: "1 (T) R&V Regt", branch_group_id: "1", branch_id: "4"},
{unit_total: 3, branch_name: "3 (T) Bn", branch_group_id: "1", branch_id: "2"}];
这里array2是多级数组,下一个值将包含group_id 2,如下所示
我想将array2值推送到array1,其键名如下所示
var result_array = [{group_id:1, group_name:test_group, child_array:[
{unit_total: 1, branch_name: "1 (T) Air Sqn", branch_group_id: "1", branch_id: "6"},
{unit_total: 1, branch_name: "1 (T) Arty Bty", branch_group_id: "1", branch_id: "5"},
{unit_total: 3, branch_name: "1 (T) Bn", branch_group_id: "1", branch_id: "1"},
{unit_total: 1, branch_name: "1 (T) R&V Regt", branch_group_id: "1", branch_id: "4"},
{unit_total: 3, branch_name: "3 (T) Bn", branch_group_id: "1", branch_id: "2"}},
{group_id:2, group_name:test_group, child_array:[
{unit_total: 1, branch_name: "1 (T) Air Sqn", branch_group_id: "2", branch_id: "6"},
{unit_total: 1, branch_name: "1 (T) Arty Bty", branch_group_id: "2", branch_id: "5"},
{unit_total: 3, branch_name: "1 (T) Bn", branch_group_id: "2", branch_id: "1"},
{unit_total: 1, branch_name: "1 (T) R&V Regt", branch_group_id: "2", branch_id: "4"},
{unit_total: 3, branch_name: "3 (T) Bn", branch_group_id: "2", branch_id: "2"}}
]];
我怎样才能做到这一点。我也尝试过使用array_push和concat方法,但没有运气。 请让我知道如何做到这一点。提前致谢
答案 0 :(得分:0)
您可以遍历array1并使用array.filter填充child_array:
var array1 = [
{ group_id: "1", group_name: 'test_group1' },
{ group_id: "2", group_name: 'test_group1' }
];
var array2 = [
{unit_total: 1, branch_name: "1 (T) Air Sqn", branch_group_id: "1", branch_id: "6"},
{unit_total: 1, branch_name: "1 (T) Arty Bty", branch_group_id: "1", branch_id: "5"},
{unit_total: 3, branch_name: "1 (T) Bn", branch_group_id: "2", branch_id: "1"},
{unit_total: 1, branch_name: "1 (T) R&V Regt", branch_group_id: "1", branch_id: "4"},
{unit_total: 3, branch_name: "3 (T) Bn", branch_group_id: "2", branch_id: "2"}];
array1.forEach(group => group.child_array = array2.filter(e => e.branch_group_id === group.group_id));
console.log(array1);