Update The Attribute Value Of An Object Using The Map Function In Es6
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'}
Solution 1:
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'
}
];
consteditSchoolName = (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",
},
];
consteditSchoolName = (schools, oldName, newName) =>
schools.map(({ name, ...school }) => ({
...school,
name: oldName === name ? newName : name,
}));
const updatedSchools = editSchoolName(schools, "YorkTown", "New Gen");
console.log(updatedSchools);
Solution 2:
You need to return the updated object:
consteditSchoolName = (schools, oldName, name) =>
schools.map(item => {
if (item.name === oldName) {
return {...item, name};
} else {
return item;
}
});
Solution 3:
consteditSchoolName = (schools, oldName, newName) =>
schools.map(({name, ...school }) => ({ ...school, name: oldName === name ? newName : name }));
You could shorten it by using a ternary.
Solution 4:
If you want to edit only the commented part:
consteditSchoolName = (schools, oldName, name) =>
schools.map(item => {
if (item.name === oldName) {
var newItem = Object.assign({},item);
newItem.name = name;
return newItem;
}
else{
return item;
}
});
Solution 5:
I wonder how come none of the answers give simple solution
consteditSchoolName = (schools, oldName, newName) =>
schools.map(school => { if (school.name === oldName) school.name = newName;
return school;
});
Post a Comment for "Update The Attribute Value Of An Object Using The Map Function In Es6"