问题
I'm new to JS and trying to use map array.prototype.map() function in my code. I need to add one property to the array's each element without changing the main object structure. I have this array of objects
const nav = [
{
name: 'Home',
title: 'Dashboard',
icon: 'home',
},
{
name: 'About',
icon: 'layout-auto',
title: 'About',
},
{
name: 'Applications',
icon: 'applications',
title: 'Applications',
},
];
after mapping through this array it also chaging main nav array's objects.
const mappedNav = (arr) => {
let newArr = arr.map(nav => {
nav.title = 'test';
return element;
});
}
mapNav(nav);
console.table(nav);
How can I add properties to the new array's objects wihout mutating them?
回答1:
You can use the spread syntax (...
). Using spread inside of an object literal will copy the (own enumerable) keys of the object into the newly created object literal ({}
). This way you're mapping each object to a new object, which has the same keys and values as the current object, along with an overwritten/new title
attribute.
const nav = [ { name: 'Home', title: 'Dashboard', icon: 'home', }, { name: 'About', icon: 'layout-auto', title: 'About', }, { name: 'Applications', icon: 'applications', title: 'Applications', } ];
const res = nav.map(obj => {
return {...obj, title: "test"};
});
console.log(res);
Note that object spread is ES9, if you want ES6, you can use Object.assign() instead, which will merge the properties of one (or more) objects into each other.
const nav = [ { name: 'Home', title: 'Dashboard', icon: 'home', }, { name: 'About', icon: 'layout-auto', title: 'About', }, { name: 'Applications', icon: 'applications', title: 'Applications', } ];
const res = nav.map(obj => {
return Object.assign({}, obj, {title: "test"});
// merge -------------(1^)-(2^)--(3^)
// (1) - the new object to return (used to make a shallow copy)
// (2) - merge obj (2) into (1)
// (3) - merge keys from {title: "test"} into the result of (2) above
});
console.log(res);
回答2:
map() function with spread operator can achieve this.
const nav = [
{
name: 'Home',
title: 'Dashboard',
icon: 'home',
},
{
name: 'About',
icon: 'layout-auto',
title: 'About',
},
{
name: 'Applications',
icon: 'applications',
title: 'Applications',
},
].map(v => ({...v, title: "test"}));
console.log(nav)
来源:https://stackoverflow.com/questions/63915352/using-map-in-the-function-is-mutating-the-main-array