有没有办法在Javascript

时间:2017-10-18 14:13:45

标签: javascript

我正在使用Javascript进行一些数据清理,我想知道是否有办法根据公共ID组合对象。

鉴于以下内容:

{"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循环(也许)和很多if,但也许还有一些方法我不知道。

我使用node.js,如果这意味着什么。也许有一个可以提供帮助的模块吗?

感谢。

1 个答案:

答案 0 :(得分: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' } ]