gpt4 book ai didi

javascript - 如何更改数组内的多个对象?

转载 作者:行者123 更新时间:2023-12-03 03:23:32 25 4
gpt4 key购买 nike

这是一个由两部分组成的问题,我似乎无法解决。第一部分要求以某种方式删除属于“Theo”的整个对象。第二部分需要通过编辑属于“Lorie”的属性值之一来更改对象。这是数组和说明:

var employees = [{
"firstName": "Von",
"lastName": "Budibent",
"email": "vbudibent0@163.com",
"department": "Sales"
}, {
"firstName": "Catherina",
"lastName": "Swalowe",
"email": "cswalowe1@example.com",
"department": "Engineering"
}, {
"firstName": "Theo",
"lastName": "Trill",
"email": "ttrill2@sina.com.cn",
"department": "Services"
}, {
"firstName": "Elsy",
"lastName": "McCrorie",
"email": "emccrorie3@netscape.com",
"department": "Legal"
}, {
"firstName": "Lorie",
"lastName": "Handsheart",
"email": "lhandsheart4@fotki.com",
"department": "Research and Development"
}]

/* Create a function called 'employeeUpdater'. employeeUpdater will loop
over the array above and perform the following:
1. If employee's first name is Theo, remove that employee because he just
got fired.
2. If the employee's first name is Lorie, change her department to 'HR'.
3. Return the updated employee array. */

我必须开始以下内容:

var employeeUpdater = () => {
for (let i = 0; i < employees.length; i++) {
if (employees[i] = 'Theo') {
employees.remove(employees[i]);
} else if (employees[i] = 'Lorie') {
employees.department = 'HR';
}
} return employees;
}

代码有问题

最佳答案

Javascript 数组没有名为 remove 的方法,您需要使用 Array#splice删除项目的方法。但我可以建议这个解决方案。

首次使用Array#filter排除名为 Theo 的对象,然后使用 Array#mapArray#forEach迭代数组并找到以 Lorie 命名的对象并更改其部门 a。

var employees = [{
"firstName": "Von",
"lastName": "Budibent",
"email": "vbudibent0@163.com",
"department": "Sales"
}, {
"firstName": "Catherina",
"lastName": "Swalowe",
"email": "cswalowe1@example.com",
"department": "Engineering"
}, {
"firstName": "Theo",
"lastName": "Trill",
"email": "ttrill2@sina.com.cn",
"department": "Services"
}, {
"firstName": "Elsy",
"lastName": "McCrorie",
"email": "emccrorie3@netscape.com",
"department": "Legal"
}, {
"firstName": "Lorie",
"lastName": "Handsheart",
"email": "lhandsheart4@fotki.com",
"department": "Research and Development"
}];

var editedEmployees = employees
.filter(emp => emp.firstName !== 'Theo')
.map(emp =>
({
"firstName": emp.firstName,
"lastName": emp.lastName,
"email": emp.email,
"department": emp.firstName === 'Lorie' ? 'HR' : emp.department
}));

console.log(editedEmployees)

关于javascript - 如何更改数组内的多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46460951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com