在函数中使用map会使主数组发生变异 [英] Using map in the function is mutating the main array

查看:45
本文介绍了在函数中使用map会使主数组发生变异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS的新手,正在尝试在代码中使用map array.prototype.map()函数.我需要在不更改主对象结构的情况下向数组的每个元素添加一个属性.我有这一系列的物体

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?

推荐答案

您可以使用

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

请注意,对象传播是ES9,如果需要ES6,则可以使用 Object.assign() 代替,它将一个(或多个)对象的属性彼此合并.

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

这篇关于在函数中使用map会使主数组发生变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆