looping through user data in an object array

Viewed 169

I'm trying to loop through multiple user's data. Shown below:

const users = [
  {
    name: 'Homer', 
    role: 'Clerk', 
    dob: '12/02/1988',
    admin: false 
  }, 
  {
    name: 'Lisa', 
    role: 'Staff', 
    dob: '01/30/1965',
    admin: false 
  }, 
  {
    name: 'Marge', 
    role: 'Associate', 
    dob: '09/10/1980',
    admin: true 
  }
];

My code is below:

let namesAndRoles = (users) => {
  for (let [key,value] of Object.entries(users)) {
    console.log(`${key}: ${value}`);
  }
};
//namesAndRoles(users)

Given an array of users, write a function, namesAndRoles that returns all of the user's names and roles in a string with each value labeled:

how do I get back users data in this form:

Name: Homer
Role: Clerk
2 Answers

value is an object which you are trying to log, you should access the specific property value like value.name.

You can try using Array.prototype.map():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

const users = [
  {
    name: 'Homer', 
    role: 'Clerk', 
    dob: '12/02/1988',
    admin: false 
  }, 
  {
    name: 'Lisa', 
    role: 'Staff', 
    dob: '01/30/1965',
    admin: false 
  }, 
  {
    name: 'Marge', 
    role: 'Associate', 
    dob: '09/10/1980',
    admin: true 
  }
];
let namesAndRoles = (users) => users.map(p => ({Name: p.name, Role: p.role}));
console.log(namesAndRoles(users));

Try reducing the users Array to a string

const users = [
  {
    name: 'Homer', 
    role: 'Clerk', 
    dob: '12/02/1988',
    admin: false 
  }, 
  {
    name: 'Lisa', 
    role: 'Staff', 
    dob: '01/30/1965',
    admin: false 
  }, 
  {
    name: 'Marge', 
    role: 'Associate', 
    dob: '09/10/1980',
    admin: true 
  }
];

console.log(users
  .reduce( (acc, val) =>
    `${acc}\nname: ${val.name}\nrole: ${val.role}\n`, ``)
  .trim()  // removes first \n)
);

Related