Home > Back-end >  Get all unique values from objects and assign them into array under correct key
Get all unique values from objects and assign them into array under correct key

Time:05-31

I have an array of objects and need to be converted to an object with array of unique values assigned to same keys

So for the sake of helping me learn, can someone help me determine how to get an this output ?

//input

let users = [
  { id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
  { id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
  { id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
  { id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
  { id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];

//output

let unique = {
  id: [1, 2, 3 ,4 ,5],
  name: ['Alan', 'John', 'Monica', 'Sandra', 'Jacob'],
  surname: ['Davis', 'Doe', 'Bush', 'Back', 'Front'],
  age: [34, 35, 25, 23],
  isAdmin: ['yes', 'no'],
}

CodePudding user response:

Here's one way

  1. Iterate over the keys of the first object in the array to produce a list of keys
  2. Create an array of the corresponding values. Filter the array for dupes.
  3. Wrap the keys and values back into an object

let users = [
  { id: 1, name: "Alan", surname: "Davis", age: 34, isAdmin: 'yes'},
  { id: 2, name: "John", surname: "Doe", age: 35, isAdmin: 'no'},
  { id: 3, name: "Monica", surname: "Bush", age: 25, isAdmin: 'no'},
  { id: 4, name: "Sandra", surname: "Back", age: 23, isAdmin: 'no'},
  { id: 5, name: "Jacob", surname: "Front", age: 34, isAdmin: 'yes'},
];

let unique = Object.fromEntries(
  Object.keys(users[0]).map(k => 
    [k, users.map(u => u[k]).filter((value, i, arr) => arr.indexOf(value) === i)]
  )
);

console.log(unique);

  • Related