删除对象数组中的元素并更改元素属性

时间:2020-05-03 00:56:21

标签: javascript

因此有一个称为雇员的对象数组,具有雇员的凭证。 如果员工的名字是Theo,我应该删除该对象,如果员工的名字是Lorie,我应该将部门的属性更改为“ HR” 我尝试过使用for循环来遍历数组中的对象并更改其属性。但它不会返回迭代数组。 也许我需要使用.reduce()方法 Here is the code I've tried

enter image description here

3 个答案:

答案 0 :(得分:0)

应该可以!

您的对象数组。

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"
 }
];

然后,您需要按firstName进行过滤,然后映射数据。

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

答案 1 :(得分:0)

//我需要使用没有参数的函数,所以我想出了怎么做。

Solved question

答案 2 :(得分:0)

//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
})