简体   繁体   中英

Deleting element and changing element property in an Array of objects

So there is an array of object called employees that has employee's credentials. I am supposed to delete the object if the employee's name is Theo, and if the employee's name is Lorie I should change the department's property to 'HR' I've tried using a for loop to go through the objects in the array and change their properties. but it would not return the iterated array. maybe I need to use the.reduce() method Here is the code I've tried

在此处输入图像描述

It should be working!

Your array of objects.

var employees = [
 {
  "firstName": 'Von',
  "lastName": 'budibent',
  "email": "email@mail.com",
  "departement": "Sales"
 },
 {
  "firstName": 'Theo',
  "lastName": 'Trill',
  "email": "email@mail.com",
  "departement": "Services"
 },
 {
  "firstName": 'Lorie',
  "lastName": 'Trill',
  "email": "email@mail.com",
  "departement": "Research and Development"
 }
];

Then you need to filter by firstName and then mapping the data.

var adjustedEmployees = employees
 .filter(employee => employee.firstName !== 'Theo')
 .map((employee) => {
   if (employee.firstName === 'Lorie') employee.departement = 'HR';
   return employee;
 });

//I needed to use a function with no parameters, I figured out how to do it.

Solved question

//Remove employe with firstname 'Theo'
var result = employees.filter(employee => employee.firstName !== 'Theo');
//Change department of Lorie to 'HR'
result.forEach(el => {
  el.departement = el.firstName === 'Lorie' ? 'HR' : el.departement
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM