0

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

How can I get 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'],
}

2 Answers 2

2

You can use Array.prototype.reduce() and for all of the items iterate over with Array.prototype.forEach() and creating a unique array with Set

Code:

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

const unique = users.reduce((a, c) => (
  Object
    .entries(c)
    .forEach(([k, v]) => a[k] = [...new Set([...(a[k] || []), v])]), 
  a
), {})

console.log(unique)

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.