Update the attribute value of an object using the map function in ES6
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);
Using destructuring
const schools = [
{
name: "YorkTown",
country: "Spain",
},
{
name: "Stanford",
country: "USA",
},
{
name: "Gymnasium Achern",
country: "Germany",
},
];
const editSchoolName = (schools, oldName, newName) =>
schools.map(({ name, ...school }) => ({
...school,
name: oldName === name ? newName : name,
}));
const updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
console.log(updatedSchools);
You need to return the updated object:
const editSchoolName = (schools, oldName, name) =>
schools.map(item => {
if (item.name === oldName) {
return {...item, name};
} else {
return item;
}
});
const editSchoolName = (schools, oldName, newName) =>
schools.map(({name, ...school }) => ({ ...school, name: oldName === name ? newName : name }));
You could shorten it by using a ternary.