Skip to content Skip to sidebar Skip to footer

Is There A Ways To Combine Objects In Javascript

I'm doing some data cleaning in Javascript, and I was wondering if there is a way to combine objects based on a common ID. Given the following: {'subject':'Hadji Singh','predicate'

Solution 1:

Use reduce method of an array:

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' } ]

Post a Comment for "Is There A Ways To Combine Objects In Javascript"