Skip to content Skip to sidebar Skip to footer

Using Map In The Function Is Mutating The Main Array

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

Solution 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);

Solution 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)

Post a Comment for "Using Map In The Function Is Mutating The Main Array"