2017-10-18 210 views
1

我正在做一些數據清理的Javascript,我想知道是否有一種方法來結合基於公共ID的對象。有沒有一種方法來結合在Javascript中的對象

考慮以下幾點:

{"subject":"Hadji Singh","predicate":"nameOfUser","id":"3f540200-58b9-40a5-91c2-faafec75216f"} 
{"subject":"Race Roger Bannon","predicate":"nameOfUser","id":"41376a49-34ee-4ed8-b5f5-3f8c92b107f8"} 
{"subject":"Jessie Bannon","predicate":"nameOfUser","id":"9575cf33-8992-4763-81bb-fc640ffa3545"} 
{"subject":"Adventurer","predicate":"departmentOfUser","id":"3f540200-58b9-40a5-91c2-faafec75216f"} 
{"subject":"Bodyguard","predicate":"departmentOfUser","id":"41376a49-34ee-4ed8-b5f5-3f8c92b107f8"} 
{"subject":"Adventurer","predicate":"departmentOfUser","id":"9575cf33-8992-4763-81bb-fc640ffa3545"} 

有沒有辦法把它弄成這個樣子?

[{id:3f540200-58b9-40a5-91c2-faafec75216f, name:Hadji Singh, department:Adventurer}, 
{id:9575cf33-8992-4763-81bb-fc640ffa3545, name:Jessie Bannon, department:Adventurer}, 
{id:41376a49-34ee-4ed8-b5f5-3f8c92b107f8, name:Race Bannon, department:Bodyguard}] 

我想兩個for循環(也許)和很多如果的,但也許有一些我失蹤的方式。

我使用node.js,如果這意味着什麼。也許有一個模塊可以提供幫助?

謝謝。

+6

請包括嘗試的解決方案,爲什麼他們沒有工作,和預期的結果。這真的會幫助我們找出你的代碼的問題。謝謝! –

+0

使用'id'作爲'HashMap'鍵並執行遞歸['Object.assign'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign )秒。儘管如此,你將不得不爲優先權設置規則。請提供更多細節,也許還有一些嘗試。 – zero298

+0

使用下劃線 - https://stackoverflow.com/questions/19480008/javascript-merging-objects-by-id – Jaybird

回答

1

使用reduce陣列的方法:

let a = [{"subject":"Hadji Singh","predicate":"nameOfUser","id":"3f540200-58b9-40a5-91c2-faafec75216f"}, 
{"subject":"Race Roger Bannon","predicate":"nameOfUser","id":"41376a49-34ee-4ed8-b5f5-3f8c92b107f8"}, 
{"subject":"Jessie Bannon","predicate":"nameOfUser","id":"9575cf33-8992-4763-81bb-fc640ffa3545"}, 
{"subject":"Adventurer","predicate":"departmentOfUser","id":"3f540200-58b9-40a5-91c2-faafec75216f"}, 
{"subject":"Bodyguard","predicate":"departmentOfUser","id":"41376a49-34ee-4ed8-b5f5-3f8c92b107f8"}, 
{"subject":"Adventurer","predicate":"departmentOfUser","id":"9575cf33-8992-4763-81bb-fc640ffa3545"}] 

let b = a.reduce((acc, val) => { 
    let id = val.id 
    let idx = acc.findIndex((e) => e.id == id); 
    let subj = { id: id } 
    let predicate = val['predicate'].split('OfUser')[0] 
    subj[predicate] = val['subject'] 
    if (-1 == idx) { 
    acc.push(subj); 
    } else { 
    acc[idx] = Object.assign(acc[idx], subj); 
    } 
    return acc 
}, []) 

console.log(b); 

//[ { id: '3f540200-58b9-40a5-91c2-faafec75216f', 
// name: 'Hadji Singh', 
// department: 'Adventurer' }, 
// { id: '41376a49-34ee-4ed8-b5f5-3f8c92b107f8', 
// name: 'Race Roger Bannon', 
// department: 'Bodyguard' }, 
// { id: '9575cf33-8992-4763-81bb-fc640ffa3545', 
// name: 'Jessie Bannon', 
// department: 'Adventurer' } ] 
相關問題