使用ES6中的map函数更新对象的属性值 [英] Update the attribute value of an object using the map function in ES6
问题描述
我正在尝试在ES6中对此进行编码.以下是我要实现的目标.假设我有一个名为schools
的对象数组.
I am trying to code this in ES6. Below is what I am trying to achieve. Let's say I have an array of objects called schools
.
let schools = [
{name: 'YorkTown', country: 'Spain'},
{name: 'Stanford', country: 'USA'},
{name: 'Gymnasium Achern', country: 'Germany'}
];
现在,我想编写一个名为editSchoolName
的函数,该函数将带有3个参数,即schools
(这是我在上面定义的数组),oldName
和name
.
Now, I want to write a function called editSchoolName
which will take 3 parameters, schools
(which is the array I have defined above), oldName
and name
.
我将在参数oldName
中传递学校的名称,并且该名称应使用参数name
中的值进行更新.
I will pass the name of the school in the parameter oldName
and that name should be updated with the value in the parameter name
.
我不想更改变量schools
的状态,因此我正在使用map
函数,该函数将返回具有更改的新数组.
I don't want to change the state of the variable schools
so I am using a map
function which will return a new array with the changes.
editSchoolName
函数将像这样被调用-
The editSchoolName
function will be called like this -
var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
在这里,名称YorkTown
应该替换为名称New Gen
.因此,数组updatedSchools
的期望值应为-
Here, the name YorkTown
should be replaced with the name New Gen
. So the expected value of the array updatedSchools
should be -
let updatedSchools = [
{name: 'New Gen', country: 'Spain'},
{name: 'Stanford', country: 'USA'},
{name: 'Gymnasium Achern', country: 'Germany'}
];
这是我的editSchoolName函数的外观-
This is how my editSchoolName function looks like -
const editSchoolName = (schools, oldName, name) =>
schools.map(item => {
if (item.name === oldName) {
/* This is the part where I need the logic */
} else {
return item;
}
});
需要帮助更改editSchoolName
函数以实现上述期望的结果.
Need help in making the change in the editSchoolName
function to achieve the above mentioned desired result.
推荐答案
尝试此操作,ES6 Object.assign()
创建数组元素的副本并更新新对象.
try this, ES6 Object.assign()
to create copy of array element and update new object.
let schools = [{
name: 'YorkTown',
country: 'Spain'
},
{
name: 'Stanford',
country: 'USA'
},
{
name: 'Gymnasium Achern',
country: 'Germany'
}
];
const editSchoolName = (schools, oldName, name) => {
return schools.map(item => {
var temp = Object.assign({}, item);
if (temp.name === oldName) {
temp.name = name;
}
return temp;
});
}
var updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
console.log(updatedSchools);
console.log(schools);
这篇关于使用ES6中的map函数更新对象的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!