What is the most efficient way to get properties from an array object?

0

Issue

I want to collect the names (Jenny, Tiffany, etc.) that are stored in every object. and these objects live in an array. I’ve used Array.prototype.every() and Array.prototype.forEach(), but I don’t think they are the right methods.

I also want to note that majority of these codes are from Codaffection. I am practicing on developing in React.

If you would like to experiment with the code, click here.

In every object, there is an id, fullname, email and etc.

Properties in Objects

This is the code that adds, edits, generates unique ids for each employee, and gets all storage data.

const KEYS = {
    employees: 'employees',
    employeeId: 'employeeId'
}

export function insertEmployee(data) {
    let employees = getAllEmployees();
    data['id'] = generateEmployeeId()
    employees.push(data)
    localStorage.setItem(KEYS.employees, JSON.stringify(employees))
}

export function updateEmployee(data) {
    let employees = getAllEmployees();
    let recordIndex = employees.findIndex(x => x.id == data.id);
    employees[recordIndex] = { ...data }
    localStorage.setItem(KEYS.employees, JSON.stringify(employees));
}

export function generateEmployeeId() {
    if (localStorage.getItem(KEYS.employeeId) == null)
        localStorage.setItem(KEYS.employeeId, '0')
    var id = parseInt(localStorage.getItem(KEYS.employeeId))
    localStorage.setItem(KEYS.employeeId, (++id).toString())
    return id;
}

export function getAllEmployees() {
    if (localStorage.getItem(KEYS.employees) == null)
        localStorage.setItem(KEYS.employees, JSON.stringify([]))
    let employees = JSON.parse(localStorage.getItem(KEYS.employees));
    //map departmentID to department title
    let departments = getDepartmentCollection();
    return employees.map(x => ({
        ...x,
        department: departments[x.departmentId - 1].title
    }))
}

This is how new employees are being added and updated.

const [records, setRecords] = useState(employeeService.getAllEmployees());

const addOrEdit = (employee, resetForm) => {
    if (employee.id == 0) employeeService.insertEmployee(employee);
    else employeeService.updateEmployee(employee);
    resetForm();
    setRecords(employeeService.getAllEmployees());
}

This is how values are being inputted and addOrEdit function is being triggered.

const initialFValues = {
  id: 0,
  fullName: "",
  email: "",
  mobile: "",
  city: "",
  gender: "male",
  departmentId: "",
  hireDate: new Date(),
  isPermanent: false
};

<Controls.Input
  name="fullName"
  label="Full Name"
  value={values.fullName}
/>
<Controls.Input
  label="Email"
  name="email"
  value={values.email}
/>
<Controls.Input
  label="Mobile"
   name="mobile"
  value={values.mobile}

/>

<Controls.Button type="submit" text="Submit" />

const handleSubmit = (e) => {
    e.preventDefault();
    if (validate()) {
      addOrEdit(values, resetForm);
    }
};

This is how I am trying to capture the names: Jenny, Tiffany, and etc.

const listOfNames = () => {
    var nameList = employeeService.getAllEmployees();
    var eachName = nameList.forEach(employee.fullName); // <- This is the problem.
    console.log("List of Employees: ", nameList);
};

If you would like to experiment with the code, click here.

Solution

You mean to use map instead of forEach.

const listOfNames = () => {
    var nameList = employeeService.getAllEmployees();
    var eachName = nameList.map(employee => employee.fullName);
    console.log("List of Employees: ", eachName);
};

This should solve it. 🙂

Answered By – Yan S. Silva

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More