2017-12-27 148 views
1

我有一個數組,我需要比較它的價值觀 - 如果有重複的 - 我想將它們存儲在陣列,例如:比較2個陣列值推只有第一個結果

obj1 = [{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"}, 
{"manager_id":2,"name":"kenny"}, 
{"manager_id":4,"name":"stan"}] 

obj2 = [{"employees_id":1,"name":"dan"}, 
{"employees_id":1,"name":"ben"},{"employees_id":1,"name":"sarah"}, 
{"employees_id":2,"name":"kelly"}] 

如果「manger_id 「===」 employees_id - 那麼結果將是:

// {1:[{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"}, 
    {"employees_id":1,"name":"dan"}, {"employees_id":1,"name":"ben"}, 
    {"employees_id":1,"name":"sarah"}]}; 

我已經試過:

var obj1 = [{ 
 
    "manager_id": 1, 
 
    "name": "john" 
 
}, { 
 
    "manager_id": 1, 
 
    "name": "kile" 
 
}, { 
 
    "manager_id": 2, 
 
    "name": "kenny" 
 
}, { 
 
    "manager_id": 4, 
 
    "name": "stan" 
 
}]; 
 

 
var obj2 = [{ 
 
    "employees_id": 1, 
 
    "name": "dan" 
 
}, { 
 
    "employees_id": 1, 
 
    "name": "ben" 
 
}, { 
 
    "employees_id": 1, 
 
    "name": "sarah" 
 
}, { 
 
    "employees_id": 2, 
 
    "name": "kelly" 
 
}]; 
 

 
var res = obj1.concat(obj2).reduce(function(r, o) { 
 

 
    r[o.manager_id] = r[o.employees_id] || []; 
 
    r[o.manager_id].push(o); 
 

 

 
    return r; 
 
}, {}); 
 

 

 
console.log(res);
.as-console-wrapper { 
 
    max-height: 100% !important; 
 
    top: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div></div>

正如你可以的「經理標識」的結果不說 - 只有一個 - 時應該有更多的

如果MANAGER_ID === employees_id //應在第一個關鍵

輸出
{1:[{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"}, 
    {"employees_id":1,"name":"dan"}, {"employees_id":1,"name":"ben"}, 
    {"employees_id":1,"name":"sarah"}]}; 

正如你可以看到有幾個共同的id

回答

3

r[o.manager_id] = r[o.employees_id] || [];在此聲明,如果管理者沒有一個EMPLOYEE_ID的陣列是該ID復位。

一種方式這樣做是正確的是:

var res = obj1.concat(obj2).reduce(function(r, o) { 
    var id; 
    if(o.hasOwnProperty('manager_id')) { 
    id = o['manager_id']; 
    } 
    else { 
    id = o['employees_id']; 
    } 

    r[id] = r[id] || []; 
    r[id].push(o); 

    return r; 
}, {}); 
+0

@ abnikr7謝謝 - 釘了它! – RoyBarOn

+0

@RoyBarOn沒問題! – abhikr7

+0

你會介意解釋一下:r [id] = r [id] || [];它代表什麼?謝謝 – RoyBarOn

2

問題依賴於這一行:

r[o.manager_id] = r[o.employees_id] || []; 

你應該記住,在你的陣列的一些對象具有manager_id和其他一些不,他們有employees_id而不是,所以你必須首先用這條線來評估:

var itemId = o.manager_id || o.employees_id; 

試試這個代碼:

var res = obj1.concat(obj2).reduce(function(r, o) { 
    var itemId = o.manager_id || o.employees_id; 
    r[itemId] = r[itemId] || []; 
    r[itemId].push(o); 


    return r; 
}, {});